Reputation: 1713
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;
}
Upvotes: 1
Views: 147
Reputation: 647
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++?
Upvotes: 0
Reputation: 476940
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';
}
Upvotes: 2