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?
cin >> plainText
reads from the input up to, but excluding, the first whitespace character. You probably want std::getline(cin, plainText)
instead.
References:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With