-1

我一直在解决一个问题。我需要扫描 a\n以结束循环并将其删除以不与其他文本一起保留在变量中。到目前为止,我有这个:

do {                                    
    scanf("%[^\n]", userinput);            //loads stdin to char[] variable  
    end = userinput[0];                    //loads one char to char variable
    scanf("%*c");                          //should remove \n
    strcpy(inputstorage[i], userinput);    //copies userinput into 2d array of 
    i++;                                   //string with \n removed
} while (end != '\n');                     //should end cycle when I hit enter

这样做是,当我按下回车键时,它会将最后一个字符保留在变量末尾。

例如我输入:' Hello'

userinput是:' Hello'

end是' H'

当我之后按 enter 时,结束变量应该包含 \n 但H由于某种原因它包含 ' '。感谢您提供的所有帮助

4

2 回答 2

2

您可以使用 scanf、getlinefgets获取行,然后使用 strcspn删除“\n”。

例如。userInfo[strcspn(userInfo, "\n")] = 0;

于 2018-10-30T12:02:48.953 回答
2

end = userinput[0];保存输入的第一个字符。 scanf("%[^\n]", userinput);没有放入 a '\n'userinput[]因此测试是否end是行尾没有用。


用于fgets()读取一行

char userinput[100];
if (fgets(userinput, sizeof userinput, stdin)) {

然后通过各种手段切断潜力'\n'

 size_t len = strlen(userinput);
 if (len > 0 && userinput[len-1] == '\n') userinput[--len] = '\0';

如果代码必须使用scanf(),

int count;
do {        
  char userinput[100];

  // Use a width limiter and record its conversion count : 1, 0, EOF
  // scanf("%[^\n]", userinput);
  count = scanf("%99[^\n]", userinput);

  // Consume the next character only if it is `'\n'`. 
  // scanf("%*c");
  scanf("%*1[\n]");

  // Only save data if a non-empty line was read
  if (count == 1) {
    strcpy(inputstorage[i], userinput);
    i++;
  } 
} while (count == 1);
// Input that begins with '\n' will have count == 0

重新形成的循环可以使用

char userinput[100];
int count;
while ((count = scanf("%99[^\n]", userinput)) == 1) {
  scanf("%*1[\n]");
  strcpy(inputstorage[i++], userinput);
}
scanf("%*1[\n]");

注意 OP 的代码'/n'while (end != '/n');. 这不是行尾字符'\n',而是一个很少使用的多字符常量。当然不是OP想要的。它还暗示警告没有完全启用。节省时间启用所有警告。@aschepler

于 2018-10-30T13:09:57.617 回答