c++ - 无法添加门以防止我的代码第二次进入 if
问题描述
这是第一个 if,我不希望我的代码第二次输入,所以我添加了一个门。我还有另一个 if,它的条件是计数器等于 3,所以你可以想象,如果我没有第一个 if 的门,我的代码将继续输入第一个 if,因为 2 在 3 之前总是。现在我的问题是什么......每当我在 if 我的代码进入无限循环时添加带有门和行 (gate=0) 的条件时。此外,如果我将门设置为与 1 不同的值,我会得到相同的无限循环。请帮我。
编辑:为了帮助我,您可以在下面找到我的代码的更好示例。谢谢 :)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file;
file.open ("file.txt");
ofstream file1;
file1.open ("file1.txt");
char counter = 0;
char ch;
char x;
string word;
string word2;
string word3;
int gate = 1;
word.clear();
while (file >> std::noskipws >> ch) {
if (ch == ' ') {
++counter;
}
else if (ch != ' ') {
counter = 0;
}
if ( (counter == 2) && (gate == 1) ) {
gate = 0;
x = file.get();
while ( x != ' ' ) {
word = word + x;
x = file.get();
}
counter = 1;
word2 = word;
word.clear();
file2 << word1 << " ";
}
if (counter == 3) {
x = file.get();
while ( x != ' ' ) {
word = word + x;
x = file.get();
}
counter = 1;
word3 = word;
word.clear();
file2 << word3 << endl;
word3.clear();
gate = 1;
}
if (file.eof()) {
break;
}
}
file.close();
file1.close();
return 0;
}
解决方案
您的无限循环可能在这里:
x = file.get();
while ( x != ' ' ){
word = word + x;
x = file.get();
}
如果到达输入流的末尾,x 将变为 EOF,这与空间不同,因此永远不会离开 while 循环。请检查 EOF 或检查 istream(文件)中的 eofbit。
推荐阅读
- oracle - Oracle 11g PLSQL 将 rowtype 转换为 Varchar2(或其他 sql 类型)并返回 Rowtype
- node.js - 在 EJS 模板中显示对象的属性
- arrays - Array-Excel VBA 中的多行
- ftrace - 将 ftrace trace.dat 文件转换为 CTF 格式以与 TraceCompass 一起使用
- dart - Dart 总是执行命令`没有这样的文件或目录`
- windows - Qt creator 无法在 Windows 10 上打开“无法初始化 Qt 平台插件”
- python - 数据帧列表上的 MinMax 缩放器
- reactjs - 使用来自 mongoDB 的数据反应 setState
- odoo - Q网...
但作为外部容器/包装器 - java - 初始化Java字符串文字给出错误