【问题标题】:scanf to fgets Cscanf 到 fgets C
【发布时间】:2011-05-12 11:12:19
【问题描述】:

说我需要读入两个名字 比如,[name name]\n ....(可能 更多[name name]\n。假设名称 可以有 19 的长度,我的代码到目前为止 是,在我的情况下,我将如何实际阻止[name name name]\n 或更多[name name name...]\n 之类的输入?我听说过 fgets() 和 fscanf,但有人会告诉我一个如何使用它们的例子吗?提前致谢。

char name1[20];
char name2[20];
for(int i=0; i < numberOfRow ; i++){
  scanf(" %s %s", name1, name2);
}

好的,所以我找到了一种方法来确保只有两个元素,但我不确定如何将它们放回变量中......

char str[50];
int i;
int count = 0;
fgets(str, 50, stdin);

i = strlen(str)-1;
for(int x=0; x < i ;x++){
  if(isspace(str[x]))
    count++;
}
if(counter > 1){
  printf("Error: More than 2 elements.\n");
}else if{
//How do i place those two element back into the variable ?
char name1[20];
char name2[20];

}

【问题讨论】:

  • 如果输入字符串超过 20 个字符,则可能出现未定义行为。请改用%20s %20s。
  • 您需要考虑在scanf 格式字符串中被width 说明符计数的空终止符NOT。一个包含 20 个字符的数组应该有一个对应的"%19s"(或"%19[")格式字符串。

标签: c validation scanf fgets


【解决方案1】:

您可以使用 strtok (string.h)。请注意,此函数会修改您的源字符串(您可以复制之前的字符串)。

strtok 示例:

char* word;

// First word:
word = strtok(str, " "); // space as the delimiter
strncpy(name1, word, sizeof(name1) - 1); 
name1[sizeof(name1) - 1] = 0;  // end of word, in case the word size is > sizeof(name1)    

// Second word
word = strtok (NULL, " ");
strncpy(name2, word, sizeof(name2) - 1);
name2[sizeof(name2) - 1] = 0;

另外,我认为你应该检查一下

【讨论】:

    【解决方案2】:

    如果您从标准输入开始,则无法停止,用户可以输入他们喜欢的内容。最好先读入所有输入,然后检查结果。

    【讨论】:

    • 我可以读整行,然后检查是否只有两个名称?
    • 视情况而定,基本上你需要检查输入以查看你得到了什么。您可以在该字符串中包含各种字符,包括数字、特殊字符等。如果您的意思是这样,我不建议在输入上使用 sscanf。
    • 到目前为止,我使用了 fgets ,得到了整行,并使用 isspace 来确定是否有超过 1 个空格...可以吗?
    【解决方案3】:

    您可以使用 fgets 读取所有行,然后解析结果。 例如:

    char name[256];
    for (int i = 0; i < numberOfRow; i++)
    {
       if (fgets(name, 256, stdin) != NULL)
       {
          // Parse string
       }
    }
    

    fgets 读取该行,直到按下 Enter。 现在你需要解析这个字符串,如果用户输入错误(如“aaa”或“aaa bbb ccc”)返回错误,否则(“aaa bbb”),拆分字符串并使用“aaa”作为name1和“bbb”名字2

    【讨论】:

    • 如果我们提供了像 test00.in test00.out 这样的测试用例文件会怎样。在这种情况下 fgets 合适吗?
    • 是的。另外,pmg 是对的,您可以将控制台用作文件。请参阅 wiki 中的示例:en.wikipedia.org/wiki/Fgets
    • fgets(line, sizeof line, stdin) 从键盘读取 .. 好吧,stdin 和 stdin 通常是键盘。
    猜你喜欢
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多