循环内的 fgets C
char in[20];
char out[20];
for(int i=0; i < nEdges ;i++){
char str[50];
fgets(str, 50, stdin);
char *result = NULL;
result = strtok(str, " ");
int count = 0;
int i = 0;
char name[2][20];
while(result != NULL){
strncpy(name[i],result,20);
result = strtok( NULL, " ");
count++;
i++;
}
if(count > 2){
errorMsg2();
}else{
i = strlen(name[1]);
for(int x=0; x < i ;x++){
if(name[1][x] == '\n')
name[1][x] = '\0';
strncpy(out,name[0],20);
strncpy(in,name[1],20);
}
您好,我正在尝试读取一行并验证只有两个元素,否则会出现错误消息。这一切都在 for 循环内,当我执行程序时,fgets 从未要求我输入。 fgets 在循环内工作吗?
char in[20];
char out[20];
for(int i=0; i < nEdges ;i++){
char str[50];
fgets(str, 50, stdin);
char *result = NULL;
result = strtok(str, " ");
int count = 0;
int i = 0;
char name[2][20];
while(result != NULL){
strncpy(name[i],result,20);
result = strtok( NULL, " ");
count++;
i++;
}
if(count > 2){
errorMsg2();
}else{
i = strlen(name[1]);
for(int x=0; x < i ;x++){
if(name[1][x] == '\n')
name[1][x] = '\0';
strncpy(out,name[0],20);
strncpy(in,name[1],20);
}
Hi, I am trying to read a line and verify rather there is only two element, else error message. This is all inside a for loop, when i execute the program, fgets never asked me for input. does fgets work inside a loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是否在循环内使用 fgets 并不重要。可能存在不同的问题。使用调试器单步调试将是最好的选择。
一个潜在的问题是将
strncpy
执行到name
的循环。如果缓冲区中有两个以上的项目,那么它将写入name
数组的范围之外。在覆盖之前(而不是之后)添加检查以避免这种可能性可能会很好。另一个可能的问题是变量
i
的使用。您可能会遇到一些范围界定问题。该变量在主循环中使用,然后通过调用strlen
在该循环内进行更新。这可能会导致主循环提前结束(取决于nEdges
的值和name[1]
的长度。在任何一种情况下,它都可能不是所需的结果。It does not matter if
fgets
is used inside a loop or not. There is likely a different issue. Using a debugger to step through it would be the best bet.One potential issue is the loop that does the
strncpy
intoname
. If there are more than two items in the buffer, then it will write outside the bounds of thename
array. It would probably be good to add a check to avoid that possibility prior to the overwrite (rather than after).Another possible issue is the use of variable
i
. You may have some scoping issues. That variable is used in the main loop and then is updated inside that loop via a call tostrlen
. That would likely cause the main loop to end early (depending on the value ofnEdges
and the length ofname[1]
. In either case, it is probably not the desired result.