C++:如何在两行中为一个字符串和一个整数分配相同的输入

C++ : How to assign the same input to a string and an integer in 2 lines?

本文关键字:一个 字符串 分配 输入 整数 两行 C++      更新时间:2023-10-16

我是C++的初学者,实际上我正在学习谷歌教程。

在第二个例子中,我的问题是:检查输入是否是数字,如果不是,则能够在错误消息中重述。

这是我用来解决这个问题的一种方法,但代码长度告诉我有一种更短的方法:

#include <cstddef>
#include <iomanip>
#include <iostream>
#include <stdlib.h>
using namespace std;
bool IsInteger(string str) {
  size_t non_num_position = str.find_first_not_of("0123456789-");
  size_t sign_position = str.find_first_of("-", 1);
  if (non_num_position == string::npos && sign_position == string::npos) {
    return true;
  }
  return false;
}
void Guess() {
  int input_number = 0;
  string input_string;
  do {
    cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
    cin >> input_string;
    if (!IsInteger(input_string)) {
      int input_string_length = input_string.size();
      cout << "Sorry but « " << input_string << " » is not a number." << endl;
      cin.clear();
      cin.ignore(input_string_length, 'n');
      continue;
    }
    input_number = atoi(input_string.c_str());
    if (input_number != -1) {
      cout << "You chose " << input_number << endl;
    }
  } while (input_number != -1);
  cout << "The End." << endl;
}
int main() {
  Guess();
  return 0;
}

以下是我尝试遵循的较短方法,但一旦分配给input_numbercin似乎就被"清空"了(因为按位运算符?):

void Guess() {
  int input_number = 0;
  string input_string;
  do {
    cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
    if (!(cin >> input_number)) {
      getline(cin, input_string);
      cout << "Sorry but " << input_string << " is not a number." << endl;
      cin.clear();
      cin.ignore(100, 'n');
      continue;
    }
    if (input_number != -1) {
      cout << "You chose " << input_number << endl;
    }
  } while (input_number != -1);
  cout << "The End." << endl;
}

解决方案:

#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
void Guess() {
  int input_number = 0;
  string input_string;
  do {
    cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
    cin >> input_string;
    try {
      input_number = stoi(input_string);
      if (input_number != -1) {
        cout << "You chose " << input_number << endl;
      }
    }
    catch (const exception&) {
      cout << "Sorry but " << input_string << " is not a number." << endl;
    }
  } while (input_number != -1);
  cout << "The End." << endl;
}
int main() {
  Guess();
  return 0;
}

第一次尝试的问题是IsInteger过于复杂和冗长。否则,你的想法是对的。你的第二次尝试不太正确。。。。一旦你从cin中读取,数据就不见了。因此,与第一次尝试一样,您需要将数据存储在字符串中。

下面是一个简短的例子,它根本不需要IsInteger:

size_t p = 0;
int input_number = std::stoi(input_string, &p);
if (p < input_string.length())
{
    cout << "Sorry but " << input_string << " is not a number." << endl;
    conitnue;
}

stoi的第二个参数告诉向整数的转换在哪里停止工作。因此,如果字符串中有非int数据(如"123abc"),则p将位于字符串末尾之前的某个位置。如果p在末尾,那么整个字符串一定是一个数字。

相关文章: