文本文件读取和动态数组中的 EMTY 空间传递问题
issue with text file reading and emty space passing in dynamic array
我需要 c++ 中的帮助,将文本从文件读取到动态数组中。
文件
Regbis
Vardenis Paverdenis
Jonas Puikuolis
Gediminas Jonaitis
Futbolas
Tadas Pilkius
Justas Julis
Tenisas
Ricerdas Berankis
我尝试了这样和另一种方式while
和getline
s.empty,但它对我不起作用。
using namespace std;
struct struktura{
char team;
char lastname;
char firstname;
} sarasas[999];
int main()
{
char x [200];
int kiek;
ifstream duomenys;
duomenys.open("duom.txt");
int row, col;
while (!duomenys.eof())
{
cout << "How many teams" << endl;
cin >> row;
int **a = new int *[row];
for (int i = 0; i < row; i++)
{
cin >> col;
a[i] = new int[col];
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
duomenys >> a[i][j];
cout << a[i][j] << " ";
}
cout << endl;
}
}
system("Pause");
return 0;
}
好的,这有很多问题。我首先对字符串使用 std::string
,对动态数组使用 std::vector
。
然后,我将努力定义数据结构至少合理一半。我认为总体思路是这样的:
struct team {
std::string name;
std::vector<std::string> players;
};
然后我会为团队定义一个operator>>
,如下所示:
std::istream &operator>>(std::istream &is, team &t) {
std::vector<std::string> players;
std::string temp;
// If we can't read a team name, return signaling failure:
if (!std::getline(is, temp))
return is;
// save the team name
t.name = temp;
// and read the player's names:
while (std::getline(is, temp)) {
if (temp.empty()) // empty line--end of this team's players
break;
players.push_back(temp);
}
t.players = players; // Write the player's names into the destination
is.clear(); // and signal success, since we read a team's data
return is;
}
从那里,我们可以读取文件中的所有团队:
std::ifstream in("teams.txt");
std::vector<team> teams { std::istream_iterator<team>{in},
std::istream_iterator<team>{} };
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 命名空间中具有.h和.cpp文件的类
- 从父命名空间重载类型
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 在命名空间中定义函数还是限定函数
- C++:对不存在的命名空间使用命名空间指令
- 通过继承类使用来自不同命名空间的运算符
- 使用命名空间时出现多个定义错误
- OpenGL相机和相机空间转型的困惑
- CUDA内核和数学函数的显式命名空间
- 打印第二列时的2d字符矢量打印空间
- 嵌套的匿名命名空间
- CMakeLists.txt中的命名空间表示法
- 类是C++中的命名空间吗
- 在命名空间中使用全局命名空间中的函数
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- '使用命名空间{嵌套在另一个命名空间中的某个命名空间}"
- 为什么 openmp 的并行不适用于矢量化色彩空间转换?
- 是否可以将函数导入命名空间,但不能导出它?
- 文本文件读取和动态数组中的 EMTY 空间传递问题