0

Can someone explain to me how to properly search for a "tab" character stored in a string class?

For example:

text.txt contents:

        std::cout << "Hello"; // contains one tab space 

User enters on prompt: ./a.out < text.txt

main.cpp:

string arrey;
getline(cin, arrey);
int i = 0;
while( i != 10){
     if(arrey[i] == "\t") // error here
     {
         std::cout << "I found a tab!!!!"
     }
     i++;
}

Since there is only one tab space in the textfile, I am assuming it is stored in index [0], but the problem is that I can't seem to make a comparison and I don't know any other way of searching it. Can someone help explain an alternative?

Error: ISO C++ forbids comparison between pointer and integer

gsamaras
  • 71,951
  • 46
  • 188
  • 305
BeginnerC
  • 119
  • 2
  • 14

3 Answers3

4

First of all, what is i? And secondly, when you use array-indexing of a std::string object, you get a character (i.e. a char) and not a string.

The char is converted to an int and then the compiler tries to compare that int with the pointer to the string literal, and you can't compare plain integers with pointers.

You can however compare a character with another character, like in

arrey[i] == '\t'
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

std::string::find() might help.

Try this:

...
if(arrey.find('\t') != string::npos)
{
    std::cout << "I found a tab!!!!";
}

More info on std::string::find is available here.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Igor Korzhanov
  • 216
  • 1
  • 6
1

Why not using what C++ library provides? You could do it like this:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
  string arrey;
  getline(cin, arrey);
  if (arrey.find("\t") != std::string::npos) {
      std::cout << "found a tab!" << '\n';
  }
  return 0;
}

The code is based on this answer. Here is the ref for std::find.


About your edit, how are sure that the input is going to be 10 positions? That might be too little or too big! If it is less than the actual size of the input, you won't look all the characters of the string and if it is too big, you are going to overflow!

You could use .size(), which says the size of the string and use a for loop like this:

#include <iostream>
#include <string>

using namespace std;

int main() {
  string arrey;
  getline(cin, arrey);
  for(unsigned int i = 0; i < arrey.size(); ++i) {
    if (arrey[i] == '\t') {
      std::cout << "I found a tab!!!!";
    }
  }
  return 0;
}
Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305