如何在C++中阅读不同的格式
How to read different formats in C++?
例如:
Adam Peter Eric
John Edward
Wendy
我想存储在3个字符串数组中(每一行代表一个数组),但我被如何逐行读取所困扰。
这是我的代码:
string name [3][3] ;
ifstream file ("TTT.txt");
for (int x = 0; x < 3; x++){
for (int i = 0; x < 3; i++){
while (!file.eof()){
file >> name[x][i];
}
}
}
cout << name[0][0];
cout << name[0][1];
cout << name[0][2];
cout << name[1][0];
cout << name[1][1];
cout << name[2][0];
}
您可以使用std::getline直接读取整行。之后,只需使用空格作为分隔符即可获得单独的子字符串:
std::string line;
std::getline(file, line);
size_t position;
while ((position =line.find(" ")) != -1) {
std::string element = line.substr(0, position);
// 1. Iteration: element will be "Adam"
// 2. Iteration: element will be "Peter"
// …
}
您可以使用std::getline()
:
std::ifstream file ("TTT.txt");
std::string line;
std::string word;
std::vector< std::vector<std::string> > myVector; // use vectors instead of array in c++, they make your life easier and you don't have so many problems with memory allocation
while (std::getline(file, line))
{
std::istringstream stringStream(line);
std::vector<std::string> > myTempVector;
while(stringStream >> word)
{
// save to your vector
myTempVector.push_back(word); // insert word at end of vector
}
myVector.push_back(myTempVector); // insert temporary vector in "vector of vectors"
}
在c++中使用stl结构(向量、映射、对)。它们通常会让你的生活更轻松,你在内存分配方面的问题也更少。
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 将"打开的CV图像"中的"颜色"转换为整数格式
- TDateTime格式在C++Builder中不会更改
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 检查不带转换的扫描格式
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- 是否可以从格式字符串中检索"width"
- clang格式:宏的缩进
- clang格式:禁用排序包含
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 将RGB图像保存为PPM格式
- 询问在设计我的手臂模拟器功能表示格式1
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 带有Protobuf序列化的C++Hazelcast:字符串不是UTF-8格式的
- 如何将strftime中的格式错误作为异常捕获
- 将CHW格式的浮点向量转换为cv::Mat
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 如何以叮当格式设置评论的行长?
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- Vulkan 中的动态顶点缓冲区格式设置