首页 > 解决方案 > 按下回车后在输入旁边打印输出

问题描述

我正在尝试制作一个显示输入单词的字长的程序。

这是它的样子:

Word   Length
Come      4
Again     5
Hair      4
The       3

基本上,一旦用户输入了单词,音节的数量就会在你按下回车之后出现。不幸的是,当您按下回车键时,cin 代码实际上会考虑回车键,因此长度输出不是在同一行,而是一个新行。

我正在尝试找到一种方法来删除 cin 制作的新行或忽略它,至少这样我可以实现所需的输出。

谢谢!

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;

实际输出:

Word  Length
Come
4
Again
5
Hair
4
The
3

标签: c++formatting

解决方案


这会做你想做的事,虽然你不能轻易回到一行,但你可以清除整个控制台并再次打印出所有内容。我的实现也将使用超过 4 个单词。

#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;
}

推荐阅读