[英]Reading two columns in CSV file in c++
我有一個兩列形式的 CSV 文件:姓名、年齡
為了閱讀和存儲信息,我這樣做了
struct person
{
string name;
int age;
}
person record[10];
ifstream read("....file.csv");
然而,當我做
read >> record[0].name;
read.get();
read >> record[0].age;
read>>name 給了我整行,而不僅僅是名字。 我怎樣才能避免這個問題,以便我可以將整數讀入年齡?
謝謝!
你可以先用std:getline
讀取整行,然后通過std::istringstream
解析它(必須是#include <sstream>
),就像
std::string line;
while (std::getline(read, line)) // read whole line into line
{
std::istringstream iss(line); // string stream
std::getline(iss, record[0].name, ','); // read first part up to comma, ignore the comma
iss >> record[0].age; // read the second part
}
下面是一個完整工作的一般示例, 它將Ideone上的CSV文件標記為Live
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
// in your case you'll have a file
// std::ifstream ifile("input.txt");
std::stringstream ifile("User1, 21, 70\nUser2, 25,68");
std::string line; // we read the full line here
while (std::getline(ifile, line)) // read the current line
{
std::istringstream iss{line}; // construct a string stream from line
// read the tokens from current line separated by comma
std::vector<std::string> tokens; // here we store the tokens
std::string token; // current token
while (std::getline(iss, token, ','))
{
tokens.push_back(token); // add the token to the vector
}
// we can now process the tokens
// first display them
std::cout << "Tokenized line: ";
for (const auto& elem : tokens)
std::cout << "[" << elem << "]";
std::cout << std::endl;
// map the tokens into our variables, this applies to your scenario
std::string name = tokens[0]; // first is a string, no need for further processing
int age = std::stoi(tokens[1]); // second is an int, convert it
int height = std::stoi(tokens[2]); // same for third
std::cout << "Processed tokens: " << std::endl;
std::cout << "\t Name: " << name << std::endl;
std::cout << "\t Age: " << age << std::endl;
std::cout << "\t Height: " << height << std::endl;
}
}
read>>name
給了我整行而不僅僅是名字。 我怎么可能避免這個問題,以便我可以讀取整數到年齡?
read >> name
會將所有內容讀入name
直到遇到空格。
如果你有一個逗號分隔的行沒有空格,那么將整行讀入name
是有意義的。
您可以使用std::getline
將整行讀取到一個字符串。 然后使用各種標記std::string
。
示例標記std::string
SO帖子:
如何在C ++中對字符串進行標記?
c ++ tokenize std string
使用標記拆分C ++ std :: string,例如“;”
非常感謝@vsoftco。 你已經解決了我長期以來的非生產性搜索問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.