【发布时间】:2019-04-15 10:16:30
【问题描述】:
我想根据/ 作为分隔符将输入数组分成三个不同的数组。
我尝试了(可能是幼稚的)方法,通过使用getchar 和while 将字符读入数组并使用计数器计算@987654327 的次数,将输入字符串存储到不同的数组中@ 出现。
根据这个数字我会使用:
if (slashcounter == 0) {
destinationarray[i++] = c;
}
将其存储到正确的数组中。下面是完整的实现。
请注意,我尝试仅使用 stdio.h 来执行此操作
#include <stdio.h>
char c;
char replace[80], toBeReplaced[80], input[80], testInput[80];
int i = 0;
int slashcounter = 0;
int main(){
puts("Enter a line of text: ");
while (( c = getchar()) != '\n'){
if (c == '/') {
slashcounter++;
}
if (slashcounter == 0) {
replace[i++] = c;
}
else if (slashcounter == 1) {
toBeReplaced[i++] = c;
}
else if (slashcounter == 2) {
input[i++] = c;
}
}
//debug purpose
puts("The arrays have the following content\n");
puts("replace[]:\n");
puts(replace);
puts("\n");
puts("toBeReplaced[]:\n");
puts(toBeReplaced);
puts("\n");
puts("input[]:\n");
puts(input);
printf("Slashcounter = %d\n",slashcounter);
return 0;
不幸的是,发生的事情是:第一个单词,即第一个斜杠之前的单词被正确存储,但其他两个是空的。
我做错了什么
当前输出与输入this/test/fails
Enter a line of text:
this/test/fails
The arrays have the following content
replace[]:
this
toBeReplaced[]:
input[]:
Slashcounter = 2
Program ended with exit code: 0
附言我还想确保/s 不在输出数组中。
感谢您的帮助。
【问题讨论】:
-
您可能对
strtok函数感兴趣。 -
至于你目前的程序,我推荐你learn how to debug your programs。密切注意变量
i及其值。并且不要忘记char字符串实际上称为 null-terminated 字节字符串。 -
我用 strtok 管理它,但这可以在
string.h中找到,我只能使用 stdio.h 和函数 getchar()、puts() 和 putchar() -
strtok 应该是用户,但它来自
string.h,请手动处理,您将需要to read input string by char和found each position of delimiter,然后是split to tokens(从0 索引到第一次出现,从“firstOccur+1”索引到第二个等等。 -
char c;必须是int。getchar()不直观地返回int,而不是char。
标签: c