我在重寫我的代碼時遇到了麻煩。
這是我的程式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char pole[100];
int i = 0;
char *token;
char *space = " \r\n";
while(fgets(pole, 100, stdin)){
int j = 0;
token = strtok(pole, space);
while (token != NULL){
if (strlen(token) > 0){
j ;
}
token = strtok(NULL, space);
}
if (strcmp(pole, "x") == 0 || strcmp(pole , "x\n") == 0){
break;
}
i = j;
}
for (int x = 0; x < i; x ){
printf("Word %d: \n", x);
}
return 0;
}
輸入:
Hello I am human
Programming
Apple moon
x
輸出:
Word 0:
Word 1:
Word 2:
Word 3:
Word 4:
Word 5:
Word 6:
但我想在開頭寫字串的數量,然后是這樣的字串(沒有“x”):
3
Hello I am human
Programming
Apple moon
得到這個
Word 0:
Word 1:
Word 2:
Word 3:
Word 4:
Word 5:
Word 6:
我試過這個來解決這個問題,但它不起作用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char pole[100];
int i = 0;
int cislo;
int cislo2 = 0;
char *token;
char *space = " \r\n";
scanf("%d", &cislo);
while (cislo2 < cislo){
while(fgets(pole, 100, stdin)){
int j = 0;
token = strtok(pole, space);
while (token != NULL){
if (strlen(token) > 0){
j ;
}
token = strtok(NULL, space);
}
}
i = j;
break;
}
for (int x = 0; x < i; x ){
printf("Word %d: \n", x);
}
return 0;
}
我不知道如何改進我的程式以獲得我想要的。請幫我。
uj5u.com熱心網友回復:
有幾件事:
- 你需要使用,
while (cislo2 <= cislo)否則你會落后一個。 - 放置
i = j在內部while回圈內。 - 如果無論如何都要中斷,為什么要使用 while 回圈(用 if 替換第二個 while 回圈)
- 數數
cislo2,否則你會陷入無限回圈
這是完整的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char pole[100];
int i = 0;
int cislo;
int cislo2 = 0;
char *token;
char *space = " \r\n";
scanf("%d", &cislo);
while (cislo2 <= cislo){
if (fgets(pole, 100, stdin)){
int j = 0;
token = strtok(pole, space);
while (token != NULL){
if (strlen(token) > 0){
j ;
}
token = strtok(NULL, space);
}
i = j;
}
cislo2 ;
}
for (int x = 0; x < i; x ){
printf("Word %d: \n", x);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/525026.html
標籤:数组C细绳
