+ 3
can someone tell me "HOW THIS CODE WORKS" please.
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string numbers[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}; string message; // input the message getline(cin, message); std::stringstream input(message); string word; while (input >> word) { if (isdigit(word[0])) { int nr = stoi(word); if (nr >= 0 && nr <= 10) cout << numbers[nr]; else cout << word; } else cout << word; cout << " "; } return 0; }
13 Antworten
+ 1
علي سعد
you know cin accept single word of input.
getline accept the a line of words. You are reading into message. This task contains input is in form includes numbers from 0 to 10 only with other words.. Now you need to split line of string into words.
streamstream input(message) ; forms a stream for "message" and
input>>word;
Reads every word into input iteratively..
isdigit(word[0]) conforms the word is a number since 2 3 0 10 are numbers. It won't be like a10. and
int nr=stoi(word); convert string form number into integer form. Number[nr] returns text equivalent of number from array... If it not a number, you don't need to convert. display as it is.
So ex:
book is 10 rupee pen is 5 rs
It reads word like
book => book
is => is
10 => ten
rupee => rupee
pen => pen
is => is
5 => five
rs => rs
It reading a words, not individual characters.
isdigits(word[0]) confroms is digit are not like book => at index 0 , b is not digit,
10 => 1 is digit at [0]. so 10 is a number..
Hope it clears...
+ 3
You input a number then the program convert it into words.
Example: if the input is 10 the program will print it in words i.e. ten
except your program doesn't work this way if the number is greater than 10
https://code.sololearn.com/cp75N8C31KwS/?ref=app
+ 2
this is my problem
+ 2
You have an array of string numbers which contains the words.
The while loop runs respectively to the input and print out the words according to their index value from your array
For example: in your array the string "ten" has an index of 10, that's why when you enter 10 it gives out the word "ten" from your array
+ 2
Josh why the compiler didn't take 1 and convert it to "one"? I mean how the compiler did it
+ 1
Josh I don't understand how he output ten.
+ 1
It didn't because your logical expression allows the program to run to each item in your array and the last item as an index value of 10.
+ 1
It converts "1" to "one", "0" to "zero", and "10" to "ten". It working on words, not on single characters... Hope it helps..
+ 1
Jayakrishna🇮🇳 so when a digit after digit take them all at once?
+ 1
Jayakrishna🇮🇳 Thank you!
0
Jayakrishna🇮🇳 One more question and thank you for your replying...if(isdigit(word[0])
why he did this..why index 0?
0
Your are wrong
It didn't because your logical expression allows the program to run to each item in your array and the last item as an index value of 10.
0
Shourya Pandey can you make it clear to me,please..