如何检测\ n然后将其删除?

时间:2018-10-30 11:55:33

标签: c newline

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

这是什么,当我按Enter时,它将最后一个字符保留在变量结尾。

例如,我输入:'Hello'

userinput中是:'Hello'

end中是'H'

当我按下回车键时,结束变量应包含\ n,但出于某些原因它应包含'H'。感谢您能提供的所有帮助

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

end = userinput[0];保存输入的第一个字符。 scanf("%[^\n]", userinput);不会在'\n'中放入userinput[],因此测试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] = '\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

相关问题