C ++ while循环重置变量?

时间:2014-08-01 20:51:37

标签: c++ loops 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] != '\0'; ++x ){
                    b[x]++;
              }}
             aa << b;
             aa >> str2;
             i++;
             }
}

输出结果为:
第一个'A'发现于:0
第一个'B'发现于:1
第一个'B'发现于:1
...
该计划永远不会升级到C.

1 个答案:

答案 0 :(得分:0)

移动线

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] != '\0'; ++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++;
   }
}

输出

first 'A' found at: 0
The stringstream is at eof.
first 'B' found at: 1
The stringstream is at eof.
first 'C' found at: 2
The stringstream is at eof.
The stringstream is at eof.
The stringstream is at eof.
The stringstream is at eof.
The stringstream is at eof.

没有块

      if ( aa.eof() )
      {
         cout << "The stringstream is at eof.\n";
         aa.clear();
      }

状态aa是这样的,它没有对这些行做任何事情:

      aa << b;
      aa >> str2;

因此,str2根本没有改变。

相关问题