I'm <attempting> to write a program without the use of arrays that allows the user to say how many people are in a classroom, and then list the names to be stored, and then re displayed with the first person (alphabetical wise) and last person, (alphabetical wise) and everyone else in the middle arbitrarily placed. I have spent about four hours trying to figure out how to do just the input/output data through fstream and im about to smash the computer. If anyone can explain why my data is saved in a bunch of weird un related numbers to the text file I would greatly appreciate it, and possibly explain how to do the alphabetical nonsense.
// This program lets the user enter a filename.
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
ifstream inputFile;
string filename;
ofstream outfile;
int number;
string name, first, end;
int students;
int count;
cout << "Please tell me how many students are in your class?";
while ( !(cin >> students) || students < 5 || students >30 ) // User input of how many students in the class
{
cout << "Error!\n";
cin.clear();
fflush(stdin);
cout << "Enter again:\n";
}
// This is where I am severely lost, I cannot figure out where to put the outfile << and what should it indicate too. Thanks to anyone who can help me... So desperate.
for (count = 1; count<= students; count ++)
{
outfile.open("names4days.txt") ;
outfile << getline(cin, name);
cout<< "Student" << count ;
cin.get();
outfile.close();
}
fflush(stdin);
cout << "Press Enter Key to end....";
cin.get();
return 0;
thank u so much for replying! however, I cannot figure out a way to allow the user to enter the names into the text file. Should I be using
outfile << getline.(cin, name)??
//I am trying to make it so the user can enter names that are being saved into the outfile.
While using the one above ^^, it will only save the fourth name, or come back in strange (might be hexadecimal code).
>.<
#include <iostream>
#include <fstream>
int main()
{
constint N = 10 ;
constchar* const file_name = "names.txt" ;
// open the file for output,
// truncate it to zero size if it exists, create it if it does not
std::ofstream file( file_name ) ;
// accept 10 names from stdin and write them into the file, one name per line
std::string name ;
for( int i = 0 ; i < N ; ++i )
{
std::cout << "name? " ;
std::getline( std::cin, name ) ; // read a name
file << name << '\n' ; // write it, followed by a new line
}
}
I'm sorry again good sir, but how come now its saving everything to the file, but with the first letter removed from everything??? I'm so sorry for bothering you
> with the first letter removed from everything???
Without seeing your code, one can only make a surmise:
You have a gratuitous std::cin.get() (or something similar, something that extracts a character from the input buffer and then throws it away) in the loop.