在C ++中添加两列的最佳方法是什么?

时间:2018-01-03 06:22:50

标签: c++

我正在尝试做家庭作业,我需要一些建议。我有一个文本文件,其中包含由...分隔的数字(两列)。例如,

    123124 , 12312512
    5133421 , 12312412

文件中会有更多行。我需要在第一列和第二列中添加所有数字(需要打印出两者)。然后,我需要添加两列。所以,我的问题是什么是完成任务的最佳方式?提前致谢。我起初在想strtok()。但是,它不起作用,因为我需要打印出第一列和第二列的总和。

2 个答案:

答案 0 :(得分:1)

您可以将值读入两个std::vector对象:

// Example input data
std::istringstream in(R"~(

123124 , 12312512
5133421 , 12312412

)~");

// you can open a file instead and none of the
// other code changes:
//
// std::ifstream in("my_data_file.csv");

std::vector<int> col_1;
std::vector<int> col_2;

int i1;
int i2;
std::string comma; // used to skip past the commas

// we read in and test the results of the read
// as the while condition
while(in >> i1 >> comma >> i2)
{
    // We know the read succeeded here so we can safely
    // append the numbers to the ends of the vectors
    col_1.push_back(i1);
    col_2.push_back(i2);
}

// Did we get all the way to the end?
if(!in.eof())
    throw std::runtime_error("bad input"); // must be an input error

// process our vectors here

std::cout << "First column: " << '\n';

for(auto i: col_1)
    std::cout << i << '\n';

std::cout << "Second column: " << '\n';

for(auto i: col_2)
    std::cout << i << '\n';

答案 1 :(得分:0)

这样的事情会起作用:

int x, y;
fscanf("%d, %d",&x, &y);

我真的不喜欢scanf(),这就是原因。这将有效:

x, y

如果您将fscanf()更改为短整数 x, y将访问无效内存(繁荣)。

如果您将fscanf()更改为 long int {{1}},则会给您不正确的结果。

鉴于这两个选择,我非常希望使用std :: istream。