-1

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.

5
  • Do not post images of text and provide a minimal reproducible example. Commented Aug 30, 2024 at 6:47
  • 2
    %s is expecting a C string, you are passing a different type - C++ string. Either use C++ file API or name.c_str(). Also enable compiler warnings to catch this error at compile time. Commented Aug 30, 2024 at 6:49
  • Also paste your csv output in your question don't link to it. Side note : Where are you learning C++ from, that is still teaching you to use a "C" FILE pointer? This is C++ so at least use std::ofstream, which works much better with all the other C++ types like std::string Commented Aug 30, 2024 at 6:50
  • 1
    You're using C functions that have no knowledge about C++ objects. What resource are you using to learn C++? Commented Aug 30, 2024 at 6:57
  • fprintf (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::ofstream to avoid this problem. Commented Aug 30, 2024 at 6:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.