C++ 如何从C+;中循环的.txt文件中读取字符串+;
我的代码:C++ 如何从C+;中循环的.txt文件中读取字符串+;,c++,C++,我的代码: #include <Windows.h> #include <iostream> #include <fstream> #include <string> using namespace std; string index[8]; int main() { int count = 0; ifstream input; //input.open("passData.txt"); while (true
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string index[8];
int main() {
int count = 0;
ifstream input;
//input.open("passData.txt");
while (true) {
input.open("passData.txt");
if (!input) {
cout << "ERROR" << endl;
system("pause");
exit(-1);
}
else {
if (input.is_open()) {
while (!input.eof()) {
input >> index[count];
count++;
}
}
for (int i = 0; i < 8; i++) {
cout << index[i] << endl;
}
}
input.close();
}
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
字符串索引[8];
int main(){
整数计数=0;
ifstream输入;
//打开(“passData.txt”);
while(true){
打开(“passData.txt”);
如果(!输入){
cout索引[计数];
计数++;
}
}
对于(int i=0;i<8;i++){
我发现这段代码的问题是,你没有像以前一样打破无休止的循环。因为你不断增加计数,它最终超出了名为索引的字符串数组的范围。看看下面的代码,我认为它完成了你的任务,但更简单:
string strBuff[8];
int count = 0;
fstream f("c:\\file.txt", ios::in);
if (!f.is_open()) {
cout << "The file cannot be read" << endl;
exit(-1);
}
while (getline(f, strBuff[count])) {
count++;
}
cout << strBuff[3] << endl;
字符串strBuff[8];
整数计数=0;
fstream f(“c:\\file.txt”,ios::in);
如果(!f.是开的()){
cout从流中提取时,应该检查结果,而不是事先进行测试
不需要调用open
,接受字符串的构造函数就可以这样做。不需要调用close
,析构函数就可以这样做
你应该只输出你读过的行
请注意,如果文件的行数不足,或者读取了8行,则应停止这两种操作
你可以放弃你写的大部分东西
#include <iostream>
#include <fstream>
#include <string>
int main()
{
string index[8];
std::size_t count = 0;
for(std::ifstream input("passData.txt"); (count < 8) && std::getline(input, index[count]); ++count)
{
// this space intentionally blank
}
for(std::size_t i = 0; i < count; ++i)
{
std::cout << index[i] << std::endl;
}
}
#包括
#包括
#包括
int main()
{
字符串索引[8];
标准::大小\u t计数=0;
对于(std::ifstream输入(“passData.txt”);(计数<8)和&std::getline(输入,索引[count]);+count)
{
//这个空格是故意空白的
}
对于(std::size\u t i=0;i std::coutinput>>索引[count];
读取一个单词(例如,直到找到空白为止的字符串)而不是一行。int count=0;
应在中定义,而(true){
loop然后按ctrl+c退出。你想要无限while循环吗?好的,显然你是对的。我忘记重置计数器了。非常感谢!它确实有一个结束:while(未到达结束点){increment}所以这不是问题:/I是指外部循环while(true)
好的,我再次阅读了您的答案,据我所知,您可能是对的。我发现了问题。正如您所说:每次while循环开始时,都需要重置计数器,以便每次循环时数组索引都从0开始。