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.
%sis expecting a C string, you are passing a different type - C++ string. Either use C++ file API orname.c_str(). Also enable compiler warnings to catch this error at compile time.FILEpointer? This is C++ so at least usestd::ofstream, which works much better with all the other C++ types likestd::stringfprintf (file , "%s,%s\n",name,number);this is wrong - this C API i unable to handle C++ types. Enable warnings as errors and compiler will tell you. Use C++std::ofstreamto avoid this problem.