2

假设我需要读取两个名称,例如[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];

}

4

3 回答 3

0

您可以使用 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;

另外,我认为你应该检查

于 2011-05-12T13:50:05.793 回答
0

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

于 2011-05-12T11:30:12.660 回答
0

您可以使用 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

于 2011-05-12T11:31:57.600 回答