如何检测 \n 然后删除它?

How to detect \n and then remove it?

我一直在处理一个问题。我需要扫描 \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'

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

你可以使用scanf, getline or fgets to get the line and then strcspn 删除"\n".

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

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


使用fgets()读一行

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

然后通过 various means.

砍掉 潜力 '\n'
 size_t len = strlen(userinput);
 if (len > 0 && userinput[len-1] == '\n') userinput[--len] = '[=11=]';

如果代码必须使用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 的代码在 while (end != '/n'); 中使用 '/n'。这不是行尾字符 '\n' 而是一个很少使用的多字符常量。当然不是 OP 想要的。它还暗示警告未完全启用。节省时间启用所有警告。 .