I am trying to obtain the first two strings from the first line of stdin using the following code.
#include <stdio.h>
#include <string.h> // for memset
int main(void) {
#define MAX_LINE_LEN 20
char heightWidth[MAX_LINE_LEN]; // allocate 50 chars to heightWidth
memset(heightWidth, 0, MAX_LINE_LEN);
fgets(heightWidth, MAX_LINE_LEN, stdin); // first line stored in heightWidth
char str1[MAX_LINE_LEN];
char str2[MAX_LINE_LEN];
memset(str1, 0, MAX_LINE_LEN);
memset(str1, 0, MAX_LINE_LEN);
int index = 0; // stores the current char index of str array
int strNumber = 1;
char currChar;
for (int i = 0; i < MAX_LINE_LEN; i++) {
if (strNumber > 2) { // if we've read two strings, break
break;
}
currChar = heightWidth[i]; // asssign current char to currChar
if (currChar == ' ') { // if current character is a space, continue
strNumber++; // increment strNumber
index = 0; // reset the index
continue;
}
// otherwise add it to one of our arrays
if (strNumber == 1) {
str1[index] = currChar;
} else {
str2[index] = currChar;
}
index++; // increment index
}
puts(str1);
puts(str2);
return 0;
}
However, when I enter three space separated strings or more, I sometimes get garbage values appended to the second string.
asdf 234 sdf // user input
asdf // first string printed is ok
234�� // second string has garbage appended
I initially though this was because the memory allocated to those arrays still had their previous values in them (hence my use of memset to "clear" them) but adding memset didn't seem to fix my issue.
What is the problem here and how can I edit my code to obtain two strings that are space separated?