Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to ASCII

Tags:

c++

ascii

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?

like image 683
E.O. Avatar asked Dec 09 '22 07:12

E.O.


2 Answers

cin >> plainText reads from the input up to, but excluding, the first whitespace character. You probably want std::getline(cin, plainText) instead.

References:

  • std::getline
  • istream& operator>> (istream& is, string& str)
like image 164
Robᵩ Avatar answered Dec 14 '22 23:12

Robᵩ


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);
like image 29
Sven Avatar answered Dec 15 '22 01:12

Sven