Home > OS >  Problem storing characters as an string inside a while loop
Problem storing characters as an string inside a while loop

Time:12-05

I'm having problems with this simple example.

The program inquires as to how many letters are required to form a complete word. Then it will ask for each letter individually, which is fine, but I can't make the code save the value from the current character and the next one from the next iteration until the number of letters finishes the word and print it to confirm the word.

E.g. Let's say house, which has 5 letters.

int numbersOfCharacters=5;
int counter=0;
char character;
string phrase;

while (counter < numbersOfCharacters)
{
    cout << "Introduce character's number" << counter << ": ";
    cin >> character;
    counter = counter   1;
    phrase=character character; //I'm not sure if I need an array here.
}

cout << "Concatenated characters: " << phrase << endl;

The output is:

Introduce the character number 1: h
Introduce the character number 2: o
Introduce the character number 3: u
Introduce the character number 4: s
Introduce the character number 5: e
Concatenated characters: ?

And the expected output should be:

Concatenated characters: house

CodePudding user response:

The expression phrase=character character; doesn't do what you think it does. You are taking the user's input, adding its numeric value to itself, and then assigning (not appending) that numeric result as a char to the string.

So, for example, on the 1st iteration, the letter h has an ASCII value of 104, which you double to 208, which is outside the ASCII range. On the next iteration, the letter o is ASCII 111 which you double to 222, which is also outside of ASCII. And so on. That is why the final string is not house like you are expecting.

Perhaps you meant to use phrase=phrase character; instead? But, that won't work either, because you can't concatenate a char value directly to a string object using operator .

What you can do is use string::operator = instead:

phrase = character;

Or the string::push_back() method:

phrase.push_back(character);

CodePudding user response:

In your code, you must declare character array and store each word in char array and also increment in index using counter veriable. below i attached a solution,

int numbersOfCharacters=5;
int counter=0;
char character;
char phrase[numbersOfCharacters];

while (counter < numbersOfCharacters)
{
    cout << "Introduce character's number" << counter << ": ";
    cin >> character; 
    phrase[counter]=character;
    counter  ;

}
cout << "Concatenated characters: " << phrase << endl;

Output: enter image description here

  •  Tags:  
  • c
  • Related