Converting string to ASCII
Solution 1
cin >> plainText
reads from the input up to, but excluding, the first whitespace character. You probably want std::getline(cin, plainText)
instead.
References:
Solution 2
The formatted input function operator>>
on istream
stops extraction from the stream if it hits a space. So your string doesn't contain the rest of the input.
If you wish to read until the end of the line, use getline
instead:
string plainText;
cout << "Enter text to convert to ASCII: ";
getline(cin, plainText);
convertToASCII(plainText);
Solution 3
Just Use getline and then no need such things you can just typecast to int a string letter to directly convert it to ascii.Here Is My Code.
#include <iostream>
#include <string>
using namespace std;
void convertToASCII(string s)
{
for (int i = 0; i < s.length(); i++)
{
cout << (int)s[i]<< endl;
}
}
int main()
{
string plainText;
cout << "Enter text to convert to ASCII: ";
getline(cin,plainText);
convertToASCII(plainText);
return 0;
}
E.O.
Updated on July 30, 2021Comments
-
E.O. over 2 years
I was just trying something out and made the following code. It is supposed to take each individual letter in a string and print its ASCII equivalent. However, when there is a space, it stops converting. Here is the code:
#include <iostream> #include <string> using namespace std; void convertToASCII(string letter) { for (int i = 0; i < letter.length(); i++) { char x = letter.at(i); cout << int(x) << endl; } } int main() { string plainText; cout << "Enter text to convert to ASCII: "; cin >> plainText; convertToASCII(plainText); return 0; }
Any ideas on why this happens?
-
Lightness Races in Orbit about 6 yearsIt's that "assumed" part that makes it a poor solution.