C fgets strtok and atoi to read a line in C

五迷三道 提交于 2020-01-06 06:40:46

问题


#include <stdio.h>
#include <string.h>

int main(void) {
    char string[10000],*token;
    int garden[100],i=0;
    fgets(string,10000,stdin);
    token = strtok(string," ");
    while(strcmp(token,"\n") != 0){
        garden[i] = atoi(token);
        i++;
        token = strtok(NULL," ");
    }
    return 0;
}

What is wrong with this code ? Why can't I read space separated integers from a line ?


回答1:


Change

 while(strcmp(token,"\n") != 0){

to

while(token != NULL){



回答2:


Your code only works when there's a space after the final number. Otherwise strcmp() never returns a non-zero value and you proceed to call it on a NULL pointer.




回答3:


Change the code in the following way:

token = strtok( string, " \n" );

while ( token != NULL && i < 100 )   
{
    garden[i] = atoi( token );
    i++;
    token = strtok( NULL, " \n" );
}



回答4:


@Igor already answered your question but please, consider alternative solution.

#include <stdio.h>

int main(void) {
    int i = 0, garden[100];
    while(i < 100 && scanf(" %d", &garden[i++]) == 1);
    return 0;
}



回答5:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
int garden[10000],length = 0,i;
char string[100];
fgets(string,100,stdin);
char *token;
token = strtok(string," ");
while (token != NULL) {
  if(strcmp(token,"\n") == 0)
    break;
  garden[length] = atoi(token);
  token = strtok(NULL," ");
  length++;
}
for(i=0; i<length;i++){
  printf("%d ",garden[i]);
}
return 0;
}

This code worked perfectly. fgets unfortunately reads the newline as well. So had to take care of that.



来源:https://stackoverflow.com/questions/26191011/c-fgets-strtok-and-atoi-to-read-a-line-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!