In: Computer Science
c++
The input items are given in one line and each item is separated by white spaces (blank-space and tab).
how can I implement?
and
input:
34 peach 7
output:
number: 34 7
string: peach
How can I separate the numbers and characters that I type at once?
#include <bits/stdc++.h>
#include <iostream>
#include <string>
using namespace std;
// function to count total words in input string
int countWords(string str)
{
istringstream is(str);
int count = 0;
// Traverse through the input string
do {
string word;
is >> word;
count++; // increase count
} while (is);
return count; // return count
}
void printNumbers(string str,int count){
istringstream is(str);
cout<<"number: ";
// Traverse through the input string
do {
string word;
is >> word;
if (isdigit(word[0]) == true){ // check if word is number
cout<<word<<" "; // if yes print number
}
} while (is);
}
void printStrings(string str, int count){
istringstream is(str);
cout<<"string: ";
// Traverse through the input string
do {
string word;
is >> word;
if (isdigit(word[0]) == false){ // check if word is number
cout<<word<<" "; // if not print string
}
} while (is);
}
// Main function
int main()
{
string input;
cout << "Please enter your input: \n";
getline (cin, input);
int count = countWords(input); // count words in string
printNumbers(input,count); // print numbers
cout<<endl;
printStrings(input,count); // print strings
return 0;
}
// Output