I am using scanf
to read a integer n and then read n strings. But it seems does not work. Here is the program:
#include <stdio.h>
#include <string.h>
#define MAX 1000
#define MAX_LEN 81
char str[MAX][MAX_LEN];
int a,i;
int main()
{
scanf("%d", &a);
for (i=0; i<a; ++i) {
scanf("%[^\n]", str[i]);
}
for (i=0; i<a; ++i)
printf("%s\n", str[i]);
}
Using %[^\\n]
I want to a sentence into a single string. What is the problem?
update: I want to input like this:
4
one
two
THREE three
FOUR four
But in fact, when I input a "4", the program then output 4 blank lines and then exits.
[walle@centos64 ~]$ ./a.out
4
_
_
_
_
where the output I expected is like this:
[walle@centos64 ~]$ ./a.out
4
one
two
THREE three
FOUR four
thans.
Use fgets
other than scanf
to get input lines. An extra getchar
is there to consume the new line after inputting the integer n
.
scanf("%d", &a);
getchar();
for (i=0; i<a; ++i) {
fgets(str[i], sizeof(str[i]), stdin);
}
for (i=0; i<a; ++i)
printf("%s", str[i]);
Note that fgets
would store the new line in the string as well. Remove it if you don't need it.
You simply need to add a space before specifier in scanf
. It will consume \\n
left in stdin and will make you able to give second input and so on.
Change to scanf(" %[^\\n]", str[i]);
and printf(" %s\\n", str[i]);
Notice the space given in scanf
.
#include <stdio.h>
#include <string.h>
#define MAX 1000
#define MAX_LEN 81
char str[MAX][MAX_LEN];
int a,i;
int main()
{
scanf("%d", &a);
for (i=0; i<a; ++i) {
scanf("%s[^\n]", str[i]);
/* scanf("%s", str[i]);*/ /*this line is also OK */
}
for (i=0; i<a; ++i)
printf("%s\n", str[i]);
}
$ gcc -g t.c
$ ./a.out
2
one
two
one
two
you missed 's' in "%s[^\\n]" before "[^\\n]".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.