【问题标题】:failing to compare space in a string无法比较字符串中的空间
【发布时间】:2012-06-09 13:16:22
【问题描述】:

我正在制作一个从用户那里获取输入的程序,而每个输入都包含用空格分隔的整数。例如“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;
            }
        }
    }

在 'if(input[i+1]==' '.....' 行中出现异常。 基本上,我试图只插入“2 2 2 2”。 我意识到,每当我尝试比较字符串中的真实空格和 ' ' 时,都会引发异常。

我尝试与空间的 ASCII 值 32 进行比较,但也失败了。 有什么想法吗?

【问题讨论】:

  • 很可能i+1超过了字符串的长度。您应该使用调试器(或添加打印语句)找出原因。
  • 你可以很容易地做到这一点,而且使用字符串流的代码要少得多。
  • 当i等于3时访问input[i+1]肯定会有问题
  • 噢,谢谢!!!我意识到当我将 cin 转换为字符串时,它会停止接收空格后的字符......!

标签: c++ string atoi


【解决方案1】:

问题是您没有在主循环中检查字符串的结尾:

for(int j=i; input[j]!=' '; j++)

应该是:

for(int j=i; input[j]!=0 && input[j]!=' '; j++)

另外,不要将 NULL 用于 NUL 字符。您应该使用'\0' 或简单地使用0。宏 NULL 只能用于指针。

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

【讨论】:

    【解决方案2】:

    不是问题的答案。

    但有两个大的评论。

    您应该注意 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
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多