Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无法比较字符串中的空格_C++_String_Atoi - Fatal编程技术网

C++ 无法比较字符串中的空格

C++ 无法比较字符串中的空格,c++,string,atoi,C++,String,Atoi,我正在制作一个程序,从用户那里获取输入,而每个输入都包含以空格分隔的整数。e、 g“2 3 4 5” 我很好地实现了atoi函数,但是,每当我尝试在字符串上运行并在空格上“跳过”时,就会出现运行时错误: for(int i=0, num=INIT; i<4; i++) { if(input[i]==' ') continue; string tmp; for(int j=i; input[j]!=' '; j

我正在制作一个程序,从用户那里获取输入,而每个输入都包含以空格分隔的整数。e、 g“2 3 4 5”

我很好地实现了atoi函数,但是,每当我尝试在字符串上运行并在空格上“跳过”时,就会出现运行时错误:

for(int i=0, num=INIT; i<4; i++)
    {
        if(input[i]==' ')
            continue;

        string tmp;
        for(int j=i; input[j]!=' '; j++)
        {
            //add every char to the temp string
            tmp+=input[j];

            //means we are at the end of the number. convert to int
            if(input[i+1]==' ' || input[i+1]==NULL)
            {
                num=m_atoi(tmp);
                i=j;
            }
        }
    }

for(int i=0,num=INIT;i问题在于您没有检查主循环中字符串的结尾:

for(int j=i; input[j]!=' '; j++)
应该是:

for(int j=i; input[j]!=0 && input[j]!=' '; j++)
另外,不要对NUL字符使用
NULL
。应使用
'\0'
或简单地使用
0
。宏
NULL
应仅用于指针

也就是说,在您的情况下,只使用
strtol
istringstream
或类似的东西可能更容易。

不是问题的答案。 但有两个大问题需要评论

您应该注意到C++流库从空间分离流中自动读取和解码int:

int main()
{
    int value;
    std::cin >> value; // Reads and ignores space then stores the next int into `value`
}
因此,要读取多个整数,只需将其放入一个循环中:

   while(std::cin >> value)   // Loop will break if user hits ctrl-D or ctrl-Z
   {                          // Or a normal file is piped to the stdin and it is finished.
        // Use value
   }
要读取一行。包含空格分隔的值,只需将该行读取为字符串(将其转换为流,然后读取值)

   std::string line;
   std::getline(std::cin, line);            // Read a line into a string
   std::stringstream linestream(line);      // Convert string into a stream

   int value;
   while(linestream >> value)               // Loop as above.
   {
        // Use Value
   }

i+1
很可能超过了字符串的长度。您应该使用调试器(或添加打印语句)来找出原因。使用stringstream,您可以非常轻松地完成此操作,并且使用更少的代码。访问
输入[i+1]肯定会有问题
当我等于3oo时,谢谢!!!我意识到当我将cin转换为字符串时,它将停止接收空格后的字符。。。!