There is a code that reads a file and writes out all the declared variables along with the types.

int _tmain(int argc, _TCHAR* argv[]) { vector <string> v(0); v.push_back("int"); v.push_back("char"); v.push_back("string"); v.push_back("mas"); v.push_back("bool"); string b; string k; ifstream file("Studying.cpp"); while (getline(file, b)) { for (int i = 0; i < b.length(); i++) { for (int j = 0; j < v.size(); j++) { if ((b.find(v[j]) != string::npos) && (b.find(";") != string::npos)) { int t = b.find(v[j]); int h = b.find(";"); k = b.substr(t, h); cout << k << endl; b.erase(t, h + 1); } else b.erase(); } } } file.close(); system("pause"); 

The problem lies in the second for loop. It checks only the first element of the vector, that is, v [0], and omits the rest. If v [j] is replaced by v [0] .. v [4], then each of the types is excellent. How to make everything output if such a cycle does not work?

  • What do you want to do with these cycles? What should be the result? What does the variable b contain after the getline call? - Vlad from Moscow
  • one
    I wonder why you have a cycle on i ? Just do the same thing many times? :) i is not used in the body of the cycle ... - Harry
  • b contains one read line from a file and searches for declared variables in it (in a clumsy way, of course). if one of the types and the ';' symbol is not found in it, then it omits the string and checks the next one, overwriting it again in the variable b. The result in the console is something like this: int a; int b; string sdk; bool fwjf; - Greto
  • You are right, you can omit it), but it still doesn’t lead to a solution to the problem - Greto
  • @Greto The question should be closed, since it is completely unclear what you want to achieve in the program, and how the input data is presented in the file. - Vlad from Moscow

1 answer 1

In addition to the mass of other nonsense, see - that you did not find the int . What's happening? The if condition if not satisfied, you go to the else and delete the entire line. And what do you want after this to look for it? ...

And - well, it just hurts to look at unnecessary searches - you endure searches before if :

  int t = b.find(v[j]); int h = b.find(";"); if ((t != string::npos) && (h != string::npos)) 

But in any case, without normal parsing, you will get a lot of nonsense. Not everything that starts with a type name and ends ; - declaration of variables ...

  • Thanks, earned. My task is not so demanding, so a similar variable declaration is enough. - Greto
  • Well, glad I could help. If my answer satisfied you - put a bird :) - Harry