I'm having trouble rewriting my code.
This is my program:
#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;
}
Input:
Hello I am human
Programming
Apple moon
x
Output:
Word 0:
Word 1:
Word 2:
Word 3:
Word 4:
Word 5:
Word 6:
But I want to write the number of strings at the beginning then the strings like this (without "x"):
3
Hello I am human
Programming
Apple moon
and get this
Word 0:
Word 1:
Word 2:
Word 3:
Word 4:
Word 5:
Word 6:
I've tried this to solve this problem, but it doesn't work
#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;
}
I have no idea how to improve my program to get what I want. Please help me.
CodePudding user response:
There are a few things:
- You need to use
while (cislo2 <= cislo)
otherwise you'll be off by one. - Place
i = j
inside the inner while loop. - Why use a while loop if you break out anyway (replace the second while loop with an if)
- Count up
cislo2
, otherwise you got yourself an infinite loop
Here is the full code:
#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;
}