[英]fgets inside a loop 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);
}
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.
这一切都在for循环内,当我执行程序时,fgets从不要求我输入。 does fgets work inside a loop?
fget在循环中起作用吗?
It does not matter if fgets
is used inside a loop or not. 是否在循环内使用
fgets
并不重要。 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
into name
. 一个潜在的问题是将
strncpy
转换为name
的循环。 If there are more than two items in the buffer, then it will write outside the bounds of the name
array. 如果缓冲区中有两个以上的项目,则它将在
name
数组的边界之外写入。 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
. 另一个可能的问题是使用变量
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 to
strlen
. 该变量在主循环中使用,然后通过调用
strlen
在该循环中更新。 That would likely cause the main loop to end early (depending on the value of nEdges
and the length of name[1]
. In either case, it is probably not the desired result. 这可能会导致主循环提前结束(取决于
nEdges
的值和name[1]
的长度。在两种情况下,这都可能不是理想的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.