Hello.

Here is a small piece of the program, which generally spoils the whole raspberry.

Option 1.

string MainStr; FILE *Storage; Storage=fopen("StorageF.txt", "wt"); std::cin>>MainStr; fprintf(Storage, "%s", MainStr); fclose(Storage); Storage=fopen("StorageF.txt", "rt"); fscanf(Storage, "%d", MainStr); std::cout<<MainStr<<"\n"; 

The program works, in the folder with it appears the file StroageF.txt which is filled, not with what I typed from the keyboard, but with some sort of meaningless combination of Russian letters.

Option 2.

 string MainStr; FILE *Storage; Storage=fopen("StorageF.txt", "rt"); fscanf(Storage, "%d", MainStr); std::cout<<MainStr<<"\n"; 

StorageF.txt is already created and filled with numbers or Latin characters, but nothing is displayed in the console where cout is working — an empty string.

Essence: I do not want to enter the string with my hands, I want the string to be filled with data from a file, which I did not do right?

    1 answer 1

    You are trying to output the string class with the C function.
    Replace:

     fprintf(Storage, "%s", MainStr); 

    on

     fprintf(Storage, "%s", MainStr.c_str()); 

    The string class's c_str () method returns const char *, which is what fprintf accepts.

    ADD:

    Yes, and why do you combine C and C ++ in one code.
    Read the string from the file.

     std::string MainStr; std::fstream file("Storage.txt"); std::getline(file, MainStr); file.close(); std::cout << MainStr.c_str(); 

    Write the string to the file.

     std::string MainStr = "Test String for file"; std::fstream file("Storage2.txt"); file << MainStr.c_str(); file.close(); 
    • Oooh, thanks) I honestly did not know what a combination of this kind was going on, I looked through the articles on the Internet for the query "String C ++", and found a fprintf, etc.) - BlackOverlord
    • And it is also a good idea to advise the author of the question to pay attention to the specifiers in printf / scanf , since %d is clearly not relevant in this case. - gecube
    • This is actually my typo, there is% s everywhere - BlackOverlord
    • @BlackOverlord Well correct the text of the question (click edit at the bottom of the question) ... - Rules