How to read input string with spaces of certain length from text file c++
我的问题是我正在尝试从文本文件中输入char,string和int。我知道如何使用getline()输入,但是在使用get line()函数之后,不再有选项可以在字符串后输入其余整数。我的问题是,如何输入一个字符,然后是一个字符串(带空格),后跟3个整数?
data.txt看起来像这样
1 2 3 | a New York 5 7 9 b Virginia 10 2 5 c Los Angeles 25 15 6 |
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | int main() { string city; double price; int amt1, amt2, amt3; char orderStatus; ifstream warehouse; ofstream output; warehouse.open("data.txt"); output.open("dataOut.txt"); while (warehouse.good()) { warehouse >> orderStatus; output << orderStatus <<"\\t"; getline(warehouse, city, '\\t'); //warehouse >> city; output << city << endl; //warehouse >> amt1; //output << amt1 <<"\\t"; //warehouse >> amt2; //output << amt2 <<"\\t"; //warehouse >> amt3; //output << amt3; } warehouse.close(); output.close(); return 0; } |
非常感谢您的帮助。
这是我对您的代码所做的修改。我添加了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string city; double price; int amt1, amt2, amt3; char orderStatus; ifstream warehouse; ofstream output; warehouse.open("data.txt"); output.open("dataOut.txt"); while (warehouse.good()) { warehouse >> orderStatus; if(!warehouse.good()) break; output << orderStatus <<"\\t"; // to skip the tab delimiter warehouse >> noskipws >> orderStatus >> skipws; if(!warehouse.good()) break; getline(warehouse, city, '\\t'); if(!warehouse.good()) break; output << city <<"\\t"; warehouse >> amt1; if(!warehouse.good()) break; output << amt1 <<"\\t"; warehouse >> amt2; if(!warehouse.good()) break; output << amt2 <<"\\t"; warehouse >> amt3; if(!warehouse.good()) break; output << amt3 << endl; } warehouse.close(); output.close(); return 0; } |
一种快速的解决方案是使用