繁体   English   中英

使用重定向在 C++ 中读取 .txt 文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM