c++ - 按下回车后在输入旁边打印输出
问题描述
我正在尝试制作一个显示输入单词的字长的程序。
这是它的样子:
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
解决方案
这会做你想做的事,虽然你不能轻易回到一行,但你可以清除整个控制台并再次打印出所有内容。我的实现也将使用超过 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;
}
推荐阅读
- r - 对数据框中的数据进行子集化以删除特定行
- wix - 未安装功能时,WiX 是否包含 Windows 服务?
- kivy - 带有 kivy 的彩色文字?
- php - array_diff() 删除部分值
- grpc - .NET Core 中使用 GRPC 的自定义标头
- google-apps-script - Google Apps脚本在创建后自动打开复制的文档?
- angularjs - .订阅函数不作为输入参数传递
- javascript - 我如何将对象的属性(在 React 中但不仅在 React 中)最好设置为一个衬里?
- reactjs - 在反应上使用调度
- javascript - 如何在函数内部返回函数?(如 p5.js createVector)