使用atoi时出错

用户名

我正在使用fgets从stdin中读取输入,然后使用atoi保存整数值。

输入:1 2 3 4

int main()
{
    char line[100];
    char *token;
    int row,column[10];
    const char split[2] = " ";

    fgets(line,100,stdin);
    token=strtok(line,split);
    row = atoi(token); //not getting any error
    while( token != NULL )
    {
        token=strtok(NULL,split);
      //  printf("column %d",atoi(token)); //getting an exception
       // column[0]= atoi(token);//error
    }
}

输出:

可执行文件

1 2

>  1 [main] a 16776 cygwin_exception::open_stackdumpfile: Dumping stack trace to a.exe.stackdump
萨胡

您使用token错误的顺序来提取值。

使用时:

while( token != NULL )
{
   token=strtok(NULL,split);
   // What happens you reach the end of the tokens and 
   // token is NULL? You are still using it in atoi.
   printf("column %d",atoi(token));
   column[0]= atoi(token);
}

您需要使用:

while( token != NULL )
{
   printf("column %d",atoi(token));
   column[0]= atoi(token);
   token=strtok(NULL,split);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章