c++appendexport-to-csv

I tried to save some strings in csv file but it gets distorted


this is my code it gets an string from user via cin and opens a file and appends it to the file resembeling a simple phonebook. what am I missing ? where am I going wrong? by the way I am using code blocks.

the phoneook.csv opened with notepad

#include <iostream>
#include <stdio.h>
#include <string.h>
using std::cin;
using std::cout;
using std::string;
using std::endl;

int main()
{
    string name;
    string number;
    cout << "Name: " ;
    cin >>  name ;
    cout << "Number: " ;
    cin >>  number;
    cout << name <<","<< number<<endl ;
    FILE *file = fopen ("phonebook.csv","a");
    if (file == NULL)
    {
        return 1;
    }
    fprintf (file , "%s,%s\n",name,number);
    fclose (file);
    return 0;
}

I checked the code by chenging string to integers and it worked. Thats why you see a number in the picture.


Solution

  • You are mixing C and C++.

    Either do it like this

    fprintf (file , "%s,%s\n",name.c_str(),number.c_str());
    

    c_str() converts a C++ string into the C string that fprintf expects.

    But better (and simpler) would be to use pure C++ for your file output.

    #include <fstream> // for ofstream
    
    std::ofstream file("phonebook.csv", std::ios_base:app);
    if (!file.is_open())
    {
        return 1;
    }
    file << name << ',' << number << '\n';
    

    This way you can use the << that you are already used to from std::cout for file output as well, instead of having to learn a whole new fprintf function.