1

hey i am a beginner in programming.so it may sound stupid. but i really don't know many things. i want to write a program where user input can be both numbers or character strings/words. if it is number, it will be processed in a way; and if it is a word, it will be processed in another way. that means i want to check the input type and work according to that! i have tried this but it isn't working!

#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;
}
Deanie
  • 2,164
  • 2
  • 14
  • 30
Nasif Imtiaz Ohi
  • 1,089
  • 3
  • 20
  • 38

2 Answers2

2

Once formatted extraction fails, your stream is in "fail" state and you can't easily process it further. It's much simpler to always read a string, and then attempt to parse it. For example, like this:

#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 */ }
}

You only need a parser function:

#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';
}
Kerrek SB
  • 428,875
  • 83
  • 813
  • 1,025
0

Alright, you need to read how cin and cout works first.

The solution to your problem will be

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

Link One: How to determine if a string is a number with C++?

Community
  • 1
  • 1
Andy Stow Away
  • 649
  • 8
  • 17