user13800925
user13800925

Reputation:

C++ printf("%s" , string) is giving me very strange output

I am trying to use printf to give my strings color with something like

printf("\x1B[92m%d\033[0m", value1);

which works for me with integers no problem, but when I try to do something like

printf("\x1B[92m%s\033[0m", wantedString);

I get random things like, (°√, any help pls?

Here is the whole function

void searchFileFor(path const& files, string wantedString) {
    
    ifstream inFile;
    string currentString;
    int lineNumber = 0;
    bool foundNothing = true;

    for (auto file : recursive_directory_iterator(files)) {
        lineNumber = 0; // Reset after each new file
        inFile.open(file);
        while (inFile >> currentString) {
            lineNumber++;
            if (currentString.find(wantedString) != string::npos) {
                cout << file << " " << wantedString << " " << lineNumber << '\n';
                foundNothing = false;
            }
            //cout << file << " " <<  currentString << endl;
        }
        inFile.close();
    }
    if (foundNothing == true) {
        cout << "We were not able to find: " << wantedString << "";
        printf("\x1B[92m%s\033[0m", wantedString);
    }
    //cout << "Wanted String: " << wantedString;
}

Upvotes: 2

Views: 5188

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12645

Printf() is a C function, accessible to C++ only for legacy code compatibility. But it is not recommended to be used in C++.

The problem you have is that you are passing a string object to it, which is something printf() is uncapable of printing. There's no relationship from a string C++ object to a char * pointer.

But you are lucky. There's a method in string (string::c_str()) that you can use, as in

 printf("\x1B[92m%s\033[0m", wantedString.c_str());

Anyway, it is better (and everybody will recommend you) to use the <iostream> C++ package, which is richer than stdio and extensible (you can overload the iostream methods to support your own data types, and that is not possible to do with printf() and friends)

Upvotes: 2

Christian Halaszovich
Christian Halaszovich

Reputation: 617

For printf you need a c-style string. Use wantedString.c_str().

Upvotes: 5

Related Questions