c++ while循环重置变量

C++ while loop resetting variables?

本文关键字:变量 循环 while c++      更新时间:2023-10-16

这是我写的一个示例程序,给出了同样的问题。
我想找到'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根本没有被改变。