1

I'm trying to make a program that displays the word length of the inputted word.

Here is what it would look like:

Word   Length
Come      4
Again     5
Hair      4
The       3

Basically, once the user inputs the word, the amount of syllables comes right after when you press enter. Unfortunately, the cin code actually takes the enter key into account when you press enter so instead of being in the same line, the length output becomes a new line.

I'm trying to find a way to either remove that new line that cin makes or ignore it, at least so I could achieve the desired output.

Thanks!

string words[4];
int wlength[4];
cout <<"word        length" <<endl;
cout << endl;
cout << "";
cin >> words[0];
wlength[0] = words[0].length();
cout << wlength[0] <<endl;
cout << "";
cin >> words[1];
wlength[1] = words[1].length();
cout << wlength[1] << endl;
cout << "";
cin >> words[2];
wlength[2] = words[2].length();
cout << wlength[2] << endl;
cout << "";
cin >> words[3];
wlength[3] = words[3].length();
cout << wlength[3] << endl;

Actual output:

Word  Length
Come
4
Again
5
Hair
4
The
3
peterchen
  • 40,917
  • 20
  • 104
  • 186
limbostack
  • 13
  • 2
  • Have you read [here] https://stackoverflow.com/questions/45134217/c-go-back-a-line ? – BrockMarekins Oct 02 '19 at 07:19
  • int wlength[4]; is redundant because string words[4]; already contains the length. (words[0].length()) Your cout << "" line is also redundant because it does not print anything and you should really use a loop rather than typing out the same code 4 times. What if you want to support a million words? – aCuria Oct 02 '19 at 08:52

1 Answers1

0

This would do what you want, while you cant go back a line easily, you CAN clear the whole console and print out everything again. My implementation will work with more than 4 words too.

#include <iostream>
#include <string>
#include <vector>
int main()
{
    std::vector<std::string> words;
    for (;;)
    {
        std::cout << "Word\t\tLength\n";
        for (auto& word : words)
            std::cout << word << "\t\t" << word.length() << "\n";

        std::string newWord;
        std::cin >> newWord;
        words.push_back(newWord);
        system("cls");
    }

    std::getchar();
    return 0;
}
aCuria
  • 6,935
  • 14
  • 53
  • 89