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

How to read from input until newline is found using scanf()?

当我应该从输入中读取内容,直到有空格,然后直到用户按下Enter时,要求我使用C进行工作。
如果我这样做:

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

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

1
I am smart

我得到的等效于:
a =" I";
b =" am";
但是应该是:
a =" I";
b ="我很聪明";

我已经尝试过:

1
2
3
scanf("%2000s %2000[^
]
"
, a, b);

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

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

warning: no closing ‘]’ for ‘%[’ format

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


scanf(和表兄弟)具有一个稍微奇怪的特性:格式字符串中(扫描集之外)的任何空格都与输入中任意数量的空格匹配。碰巧的是,至少在默认的" C"语言环境中,新行被分类为空白。

这意味着结尾的'
'
不仅试图匹配换行符,而且还试图匹配任何后续的空格。在您告知输入结束或输入一些非空白字符之前,不会认为它匹配。

为了解决这个问题,您通常需要执行以下操作:

1
2
3
4
5
6
7
8
9
scanf("%2000s %2000[^
]%c"
, a, b, c);

if (c=='
'
)
    // 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.


1
2
scanf("%2000s %2000[^
]"
, a, b);


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

1
2
3
4
5
6
7
8
while(x = getchar())
{  
    if(x == '
'
||x == '\0')
       do what you need when space or return is detected
    else
        mystring.append(x)
}

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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] == '
'
) {
      break;
    }
    else {
      i++;
    }
  }
  a[i] = '\0';
  i = 0;
  printf("
"
);
  while (a[i] != '\0') {
    printf("%c", a[i]);
    i++;
  }
  free(a);
  getch();
  return 0;
}


我为时已晚,但是您也可以尝试这种方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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=='
'
){
            break;
        }
    }
    for(j=0; j<i; j++) {
        printf("%d", arr[j]);
    }

    return 0;
}

听起来像是一个作业问题。 scanf()是用于此问题的错误函数。我建议getchar()或getch()。

注意:我故意不解决问题,因为这看起来像是作业,而只是指向正确的方向。


1
2
3
4
5
6
7
8
#include <stdio.h>
int main()
{
    char a[5],b[10];
    scanf("%2000s %2000[^
]s"
,a,b);
    printf("a=%s b=%s",a,b);
}

只需写s代替 n :)