c++ while循环重置变量
C++ while loop resetting variables?
这是我写的一个示例程序,给出了同样的问题。
我想找到'A', 'B'和'C'在哪里。
#include <iostream>
#include <sstream>
#include <string>
char a;
char b[256];
string str2 = "A";
string fileline1 = "ABC"
int i;
int x;
stringstream aa;
int main(){
while ( i < 7 ){
std::size_t found = fileline1.find(str2);
if (found!=std::string::npos){
cout << "first '" << str2 << "' found at: " << found << 'n';
strcpy(b, str2.c_str());
for ( int x=0; b[x] != ' '; ++x ){
b[x]++;
}}
aa << b;
aa >> str2;
i++;
}
}
输出为:
第一个"A"出现在:0
第一个"B"出现在:1
第一个"B"出现在:1
…
移动行
stringstream aa;
在
行之前 aa << b;
为我解决了这个问题。
这可能是由于使用aa
作为输入流和输出流引起的。不确定细节
这是你的程序,里面有一些错误检查代码。
#include <iostream>
#include <sstream>
#include <string>
#include <string.h>
using namespace std;
char a;
char b[256];
string str2 = "A";
string fileline1 = "ABC";
int i;
int x;
stringstream aa;
int main()
{
while ( i < 7 )
{
std::size_t found = fileline1.find(str2);
if (found!=std::string::npos)
{
cout << "first '" << str2 << "' found at: " << found << 'n';
strcpy(b, str2.c_str());
for ( int x=0; b[x] != ' '; ++x )
{
b[x]++;
}
}
aa << b;
if ( !aa.good() )
{
cout << "The stringstream is not good.n";
}
aa >> str2;
if ( aa.eof() )
{
cout << "The stringstream is at eof.n";
aa.clear();
}
if ( !aa.good() )
{
cout << "The stringstream is not good.n";
}
i++;
}
}
输出<>之前在:0找到的第一个"A"stringstream在eof。第一个"B"出现在:1stringstream在eof。第一个"C"出现在stringstream在eof。stringstream在eof。stringstream在eof。stringstream在eof。stringstream在eof。之前不带块
if ( aa.eof() )
{
cout << "The stringstream is at eof.n";
aa.clear();
}
状态aa
是这样的,它没有对以下行做任何事情:
aa << b;
aa >> str2;
因此,str2
根本没有被改变。
相关文章:
- 在循环中按顺序遍历成员变量
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 与 for 循环中的变量混淆
- 如何在循环之外重新输入变量
- 如何使用将字符串拆分为 for 循环中的变量的程序
- 在变量声明中使用 for 循环
- C++ 和 Boost.Python - 如何将变量公开给 python 并在循环中更新它?
- C++ Code 在 for 循环期间不会累积变量中的总和,仅提供最终迭代值
- C++ 在循环中添加计数器变量并再次初始化其值
- (C++)虽然循环一次不起作用,但我引入了多个变量
- 如何添加循环期间分配的变量?
- C++,每个循环初始化一个新的静态变量
- 在 for 循环中更新两个变量时遇到问题C++
- 循环中的变量被设置为下一个数组的元素始终具有相同的内存地址?
- 需要循环帮助以迭代方式添加到程序集中的总和变量
- 在 c++ 中基于范围的 for 循环中使用引用作为控制变量
- 如何在循环中动态创建变量(c++)
- 变量循环范围会导致返回局部变量的地址引用
- ifstream变量循环不打印任何内容
- c++变量/循环问题