【问题标题】:atoi() keeps returning a 0 [closed]atoi() 不断返回 0 [关闭]
【发布时间】:2013-06-12 07:26:26
【问题描述】:

在我编写的代码中,我接收一个字符串,检查它是否只包含十进制数字,然后将字符串转换为 int。但是,在我的代码中,atoi 返回一个 0,而不是作为 int 的字符串。谁能告诉我哪里搞砸了?

while (!sucess || 0 == Entries){
  delete [] bufferptr;
  buffer = nullptr;
  buffer = new char [MAX];
  bufferptr = buffer;

  cin.getline(buffer, MAX, '\n');


  while (*buffer){
    if (isdigit(*buffer++)){
      success = true;
    } else {
      success = false;
      break;
    }
  }
  if (success){
    numEntries = atoi(buffer);
    cout << endl << numEntries << endl;
    }
  }      

【问题讨论】:

  • 做一些调试,好吗? Stack Overflow 不是人工云调试服务。

标签: c++ pointers user-input atoi


【解决方案1】:

请记住,对于isdigit(*buffer++),您首先调用isdigit 并使用*buffer 的值,然后将指针加一。

if (isdigit(*buffer++))

通过这一行,您已经在字符 数字之后。

所以你应该在你不成功的时候增加,在你成功的时候打破。

...正如评论所建议的,尝试自己进行一些调试。你的 bug 并不难调试,即使有一些 cout 并且没有调试器等等(尝试在你的 while 循环中插入一个 cout &lt;&lt; buffer &lt;&lt; endl

【讨论】:

    【解决方案2】:

    您可以使用提取运算符将流内容直接解析为int

    std::cin >> numEntries;
    

    有关错误检查,请阅读http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 2017-09-13
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      相关资源
      最近更新 更多