1

嘿,我是编程的初学者。所以这听起来很愚蠢。但我真的不知道很多事情。我想编写一个程序,其中用户输入可以是数字或字符串/单词。如果是数字,则以某种方式处理;如果它是一个单词,它将以另一种方式处理。这意味着我想检查输入类型并根据它工作!我已经尝试过了,但它不起作用!

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int main()
{
    int number;
    string word;
    cout<<"enter a number or a word\n";
    while(cin>>number || cin>>word){
    if(cin>>number){
        cout<<number<<"\n";}
    if(cin>>word){
        cout<<word<<"\n";}
    }
    return 0;
}
4

2 回答 2

2

一旦格式化提取失败,您的流就处于“失败”状态,您无法轻松地进一步处理它。总是读取一个字符串,然后尝试解析它要简单得多。例如,像这样:

#include <iostream>
#include <string>

for (std::string word; std::cin >> word; )
{
    long int n;
    if (parse_int(word, n)) { /* treat n as number */ }
    else                    { /* treat word as string */ }
}

您只需要一个解析器功能:

#include <cstdlib>

bool parse_int(std::string const & s, long int & n)
{
    char * e;
    n = std::strtol(s.c_str(), &e, 0);
    return *e == '\0';
}
于 2012-07-17T07:33:01.700 回答
0

好吧,您需要先阅读如何cincout工作。

您的问题的解决方案将是

1) Declare a single string variable eg: var_input
2) Take input only once (using cin>>var_input)
3) Check if the string is a number or a word taking help from Link One

链接一: 如何用C++判断一个字符串是否为数字?

于 2012-07-17T07:41:42.347 回答