0

I am writing a simple program in C to assign two separate user inputs to separate arrays, and then concatenating the arrays.

However, I have found that if a space is included in the user-inputted string one word is assigned to array 1, and the other to array 2. My code is below.

char str1[SIZE];
char str2[SIZE];
char str3[SIZE2];

printf("Enter a string: ");
scanf("%s", str1);

printf("\nEnter another: ");
scanf("%s", str2);

printf("\n\nInput 1: %s\n", str1);
printf("Input 2: %s\n", str2);

Here's the code in execution

As can be seen, if a space is input in the first scanf() the second scanf() is 'skipped' and the words are sparated into str1[] and str2[]. I am wondering what is causing this and is there a more elegant way of accomplishing my goal?

SIZE is defined as 50 and SIZE2 as 100

Cal B
  • 3
  • 3

2 Answers2

1

To take input of a string with spaces use scanf("%[^\n]s", str1); and your program will work. Use scanf(" %[^\n]s", str2); for str2. It basically means read the string until a newline is encountered.

Shridhar R Kulkarni
  • 6,653
  • 3
  • 37
  • 57
0

Try

 fgets( str1, sizeof(str1), stdin );

fgets() accepts space as a character. And also, if a user enter a string greater in length than what is allowed, scanf() causes a segment fault but fgets() ignores character overflow and accepts just what was allocated for that variable.

Nguai al
  • 958
  • 5
  • 15
  • Great, that's worked perfectly! I just followed a link another user left to a similar question (I had searched for this question... couldn't find it) and they gave a similar answer. – Cal B Apr 15 '17 at 18:12