gpt4 book ai didi

.txt 文档与数组之间的 C++ 问题

转载 作者:行者123 更新时间:2023-11-30 02:38:35 26 4
gpt4 key购买 nike

我正在做一项作业,从 .txt 文档中的姓名列表中提取数据(每行一个,每行以逗号结尾)

我想要的是:

  • 数一数有多少行

  • 使用计数来定义数组的大小来保存单词

  • 从列表中随机选择两个单词并打印出来。

这是我的代码:

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main() {
srand(time(NULL));
int j;
int rand1 = rand() % 5;
int rand2 = rand() % 5;

ifstream myfile ("NAMES.txt");

if (myfile.is_open()) {
myfile.unsetf(ios_base::skipws);

unsigned line_count = count(
istream_iterator<char>(myfile),
istream_iterator<char>(),
'\n');
j = line_count;

cout << j << endl;

string *MN1 = new string[j];

for(int i = 0; i <= j; i++) {
getline(myfile, MN1[i], ',');
}
cout << rand1 << endl;
cout << MN1[rand1] << " " << MN1[rand2] << endl;
}
else {
cout << "Unable to open file" << endl;
}
}

但是,在代码读取行数、将其用作数组的大小,然后打印随机单词之间似乎出现了问题。

最佳答案

没有必要对文件进行两次解析,您可以使用 myfile.ignore 来忽略尾随的结束行,否则会污染您的输出。也没有必要在堆上分配您的字符串,这通常是最好避免的。下面是使用此技术的示例解决方案。

#include <fstream>
#include <iostream>
#include <string>
#include <time.h>

using namespace std;

int main()
{
srand(time(NULL));
int j;
int rand1 = rand() % 5;
int rand2 = rand() % 5;

ifstream myfile("NAMES.txt");

if (myfile.is_open()) {
myfile.unsetf(ios_base::skipws);

string str;
for (int i = 0; !myfile.eof(); i++)
{
getline(myfile, str, ',');
myfile.ignore(1);

if (i == rand1 || i == rand2) {
cout << str << endl;
}
}


}
else {
cout << "Unable to open file" << endl;
}
}

关于.txt 文档与数组之间的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30689420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com