如何使用 scanf() 从输入中读取内容直到找到换行符?

问题描述 投票:0回答:8

我被要求用 C 语言做一项工作,我应该从输入中读取数据,直到出现空格,然后直到用户按下 Enter 键。 如果我这样做:

scanf("%2000s %2000s", a, b);

它将遵循第一条规则,但不遵循第二条。
如果我写:

我很聪明

我得到的相当于:
a =“我”;
b =“上午”;
但应该是:
a =“我”;
b =“我很聪明”;

我已经尝试过:

scanf("%2000s %2000[^\n]\n", a, b);

scanf("%2000s %2000[^\0]\0", a, b);

在第一个中,它等待用户按 Ctrl+D (发送 EOF),这不是我想要的。 在第二个中,它无法编译。根据编译器的说法:

警告:‘%[’格式不能关闭‘]’

有什么好的办法解决这个问题吗?

c format scanf
8个回答
52
投票

scanf
(和表兄弟)有一个稍微奇怪的特征:格式字符串中(大多数放置在其中)的空格与输入中任意数量的空格匹配。碰巧的是,至少在默认的“C”语言环境中,换行符被归类为空白。

这意味着尾随的

'\n'
不仅尝试匹配 a 换行符,还尝试匹配任何后续的空格。在您发出输入结束信号或输入一些非空白字符之前,它不会被视为匹配。

解决这个问题的一种方法是这样的:

scanf("%2000s %2000[^\n]%c", a, b, &c);

if (c=='\n')
    // we read the whole line
else
    // the rest of the line was more than 2000 characters long. `c` contains a 
    // character from the input, and there's potentially more after that as well.

根据情况,您可能还想检查

scanf
的返回值,它告诉您成功的转换数量。在这种情况下,您需要寻找
3
来指示所有转换均已成功。


13
投票
scanf("%2000s %2000[^\n]", a, b);

5
投票

使用 getchar 和一段时间,看起来像这样

while(x = getchar())
{   
    if(x == '\n'||x == '\0')
       do what you need when space or return is detected
    else
        mystring.append(x)
}

抱歉,如果我写了伪代码,但我有一段时间不使用 C 语言了。


3
投票
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int main(void)
{
  int i = 0;
  char *a = (char *) malloc(sizeof(char) * 1024);
  while (1) {
    scanf("%c", &a[i]);
    if (a[i] == '\n') {
      break;
    }
    else {
      i++;
    }
  }
  a[i] = '\0';
  i = 0;
  printf("\n");
  while (a[i] != '\0') {
    printf("%c", a[i]);
    i++;
  }
  free(a);
  getch();
  return 0;
}

3
投票

我来得太晚了,但你也可以尝试这个方法。

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i=0, j=0, arr[100];
    char temp;
    while(scanf("%d%c", &arr[i], &temp)){
        i++;
        if(temp=='\n'){
            break;
        }
    }
    for(j=0; j<i; j++) {
        printf("%d ", arr[j]);
    }

    return 0;
}

0
投票
#include <stdio.h>
int main() {
  char line[2000] = {'\0'};
  char word[2000] = {'\0'};
  while (fgets(line, 2000, stdin) != NULL) {
    // line now contains the entire line

    sscanf(line, "%s", word);
    // word now contains the first word
  }
  return 0;
}

-1
投票
#include <stdio.h>
int main()
{
    char a[5],b[10];
    scanf("%2000s %2000[^\n]s",a,b);
    printf("a=%s b=%s",a,b);
}

只需写 s 代替 :)


-2
投票

//如果您想要更多,请增加字符数组大小。字符数。

#include <stdio.h>
int main()
{
    char s[10],s1[10];
    scanf("\n");//imp for below statement to work
    scanf("%[^\n]%c",s);//to take input till the you click enter
    scanf("%s",s1);//to take input till a space
    printf("%s",s);
    printf("%s",s1);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.