[英]Reading .txt file in C++ using redirect
我正在嘗試讀取 .txt 文件。 我的任務是只使用:
#include <iostream>
我必須使用重定向。
多行數據,例如:
AddItem 3 1 1 4 7.75 7.62 0.69 0.025 4.97 2 0 8
文件中存在。
我需要將“AddItem”作為 Char 數組讀入,並將值作為整數和雙精度數讀入。 這是我的代碼。
#include <iostream>
using namespace std;
void emptyString(char* x, int size) {
for (int i = 0; i < size; i++)
x[i] = '\0';
}
int main() {
char command[10];
int quantity, code, brand, type, option, option2;
double height, length, width, weight, price;
while (!cin.eof()) {// while end of file is not reached
emptyString(command, 10);
cin >> command
>> quantity
>> code
>> brand
>> height
>> length
>> width
>> weight
>> price
>> type
>> option
>> option2;
if (!cin.eof()) {
cout << command << ", "
<< quantity << ", "
<< code << ", "
<< brand << ", "
<< height << ", "
<< length << ", "
<< width << ", "
<< weight << ", "
<< price << ", "
<< type << ", "
<< option << ", "
<< option2 << ", "
<< endl;
}
}
return 0;
}
當我運行文件時,它永遠不會結束。 ctrl+z 應該停止它,但這對我在 Visual Studio 2015 中沒有任何作用。
我會嘗試這樣的事情:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using std::cout; using std::endl;
using std::cin; using std::getline;
using std::string; using std::istringstream;
using std::vector;
void process_command(const string& cmd, const vector<double>& args);
int main()
{
string line, command;
while (getline(cin, line)) { //read input one line at a time
istringstream ss(line); //use stringstream to read from the line
ss >> command;
vector<double> args;
double cur_arg;
while (ss >> cur_arg) //read arguments until we hit the end
args.push_back(cur_arg); //add argument to vector
//process the command
process_command(command, args);
}
return 0;
}
void process_command(const string& cmd, const vector<double>& args)
{
cout << "Command: " << cmd << "\n"
<< "Arguments: ";
for (auto s : args)
cout << s << " ";
cout << endl;
}
示例輸入:
AddItem 3 1 1 4 7.75 7.62 0.69 0.025 4.97 2 0 8
DoStuff 37 -123 0.235
DoMoreStuff 7 1e6 23 0.418
示例輸出:
Command: AddItem
Arguments: 3 1 1 4 7.75 7.62 0.69 0.025 4.97 2 0 8
Command: DoStuff
Arguments: 37 -123 0.235
Command: DoMoreStuff
Arguments: 7 1e+06 23 0.418
也許這會給你一些想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.