【发布时间】:2020-01-18 21:06:24
【问题描述】:
我最近提交了一个作业,我开始使用 VS 代码和 Ubuntu WSL 终端和 G++ 编译器,但不得不切换到 Visual Studio 2019,因为当我在同一行输出多个字符串时,它们会相互覆盖.任务让我从文件中读取数据并将每个元素放入“Car”对象的“ArrayList”(我们自制的矢量类)中,并将每个汽车元素输出给用户。我们还必须搜索汽车列表以查找某些型号的汽车并打印该型号的所有汽车。我不仅不能在同一行上计算出所有这些元素,而且不能相互比较元素(字符串)。为什么这只发生在 Ubuntu 上?为什么我不能用 std::cout.flush(); 清除 cout 缓冲区?或 std::cout
我尝试以多种方式刷新系统(正如我从其他帖子中发现的那样),例如:std::cerr、std::cout
这是我的(缩短的)cars.data(.data 是分配的要求),其中包含要存储到“ArrayList”中的所有汽车元素:
1
Tesla
Model 3
Black
2
Chevrolet
Volt
Grey
3
Tesla
Model S
White
4
Nissan
Leaf
White
5
Toyota
Prius
Red
我将每个元素存储到“ArrayList”中的实现:
ArrayList cars_list(15);
std::fstream cars;
cars.open("cars.data");
int tempID;
std::string tempIDstr;
std::string tempMake;
std::string tempModel;
std::string tempColor;
if (cars.is_open())
{
for (int i = 0; !cars.eof(); ++i)
{
std::getline(cars, tempIDstr);
tempID = std::stoi( tempIDstr );
std::getline(cars, tempMake);
std::getline(cars, tempModel);
std::getline(cars, tempColor);
Car tempCar(tempID, tempMake, tempModel, tempColor);
std::cout.flush();
std::cout << tempIDstr << " ";
std::cout.flush();
std::cout << tempMake << " ";
std::cout.flush();
std::cout << tempModel << " ";
std::cout.flush();
std::cout << tempColor << " " << std::endl;
cars_list.push_back(tempCar);
}
}
cars.close();
还有一个我用来比较字符串来搜索列表的函数:
void searchByMake(ArrayList list)
{
std::string make;
std::cout << "Enter the make you would like to search: ";
std::cin >> make;
std::cin.clear();
std::cin.ignore(10000,'\n');
// Searching through the cars_list for the Make
for (int i = 0; i < list.size(); ++i)
{
Car tempCar = list.get(i);
if (make.compare(tempCar.getMake()) == 0)
{
std::cout << "ID:\t" << tempCar.getID() << "\n"
<< "Make:\t" << tempCar.getMake() << "\n"
<< "Model:\t" << tempCar.getModel() << "\n"
<< "Color:\t" << tempCar.getColor() << "\n\n";
}
}
}
第一段代码的结果是(我注意到每个输出前的空格):
Black 3
Greyvrolet
White S
Whitean
Redusta
预期的输出应如下所示:
1 Tesla Model 3 Black
2 Chevrolet Volt Grey
3 Tesla Model S White
4 Nissan Leaf White
5 Toyota Prius Red
每当我尝试比较字符串时,输出都会返回一个空行:
Enter the make you would like to search: Tesla
预期的输出是:
Enter the make you would like to search: Tesla
id: 1
Make: Tesla
Model: Model 3
Color: Black
id: 3
Make: Tesla
Model: Model S
Color: White
我的老师提到问题可能是 Ubuntu 本身即使在提示时也无法清除缓冲区,但我仍然找不到解决方案。仅供参考,这是一个已通过的作业,我无法再获得荣誉,这个问题完全是出于好奇和仍然使用 Ubuntu WSL 作为我的开发终端的愿望。
【问题讨论】:
-
“我会在同一行输出几个字符串,它们会相互覆盖”...您是否偶然在 windows 下创建了文件并且它有嵌入式
'\r'(回车——就像旧打字机一样——将马车返回到起始位置?) -
这是输入文件使用
\r\n换行符的明显案例 -
除非有什么特别的事情发生,否则不要使用
cout.flush。相反,如果你真的想刷新一行,只需使用std::cout << std::endl
标签: c++ linux string ubuntu cout