Home > Enterprise >  C printf("%s" , string) is giving me very strange output
C printf("%s" , string) is giving me very strange output

Time:12-08

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;
}

CodePudding user response:

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

  • Related