我试图使用以下代码从stdin的第一行获取前两个字符串。
#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;
}
但是,当我输入三个空格分隔的字符串或更多时,我有时会将垃圾值附加到第二个字符串。
asdf 234 sdf // user input
asdf // first string printed is ok
234�� // second string has garbage appended
我最初虽然这是因为分配给这些数组的内存仍然具有它们之前的值(因此我使用memset来&#34;清除&#34;它们)但添加memset似乎没有解决我的问题。
这里有什么问题,如何编辑我的代码以获得两个空格分隔的字符串?
答案 0 :(得分:4)
你有一个拼写错误,而不是将第二个字符串归零,而是将第一个字符串归零。
答案 1 :(得分:1)
抛弃memset
次调用(其中一次有错误,因为你要设置两次相同的数组),然后写
char str1[MAX_LINE_LEN] = {0};
和C。代替。这将零初始化数组中的所有元素。这优于使用memset
:
str1
和str2
永远不会处于未初始化状态。sizeof
成语)来判断它。