Input txt file:
Joe Smith
Mary Jones
Hamid Namdar
Desired Output Txt file:
Smith Joe
Jones Mary
Namdar Hamid
Output file I receive:
SmitJoeJonesMaryNamdarHamid
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ofstream output;
ifstream input;
string firstname, lastname;
output.open("LastName.txt");
input.open("FirstName.txt");
cout << "Processing Data..." << endl;
input >> firstname >> lastname;
cout << firstname << lastname << endl;
output << lastname << firstname;
cout << lastname << firstname << endl;
input >> firstname >> lastname;
cout << firstname << lastname << endl;
output << lastname << firstname;
cout << lastname << firstname << endl;
input >> firstname >> lastname;
cout << firstname << lastname << endl;
output << lastname << firstname;
cout << lastname << firstname << endl;
input.close();
output.close();
cin.get();
cin.get();
return 0;
}
My program is required to have spaces between the names, and even though there is a space in my text document, the spaces are not being read. Does anyone have an idea on what I should do in order to have the spaces be read?
I am guessing that you would like to see spaces in your output but you are not getting them. That makes you think that the spaces are not being read. The truth is that the white spaces are being read but are being discarded when you use:
input >> firstname >> lastname;
You need to change the lines that create the output to:
cout << firstname << " " << lastname << endl;
output << lastname << " " << firstname << endl;
Related
I have a question about my program that I am creating in C++ Visual Studios. First what I want to do is get all the Info about Accounts inputted from the user, then Displayed back to the user to make sure it was entered correctly. Then put that information into the file AccountInformation.txt. I have gotten it to all work up until now it's going from doing this fine cin >> Street then it will group the next two cin's together so I don't know why its doing that. here is the code and the sample output of the program as it runs now.
// CreateWriteDisplay.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <fstream>
#include <iostream>
#include <string>
#include <ostream>
using std::cout; //using namespace std is not a good practice **
using std::cin; //it's best to use std:: scope or using only what you need
using std::string; //not the whole namespace, C++17 allows for comma
using std::endl; //separated usings
using namespace std;
// Declares all the variables I need.
int AccountAge;
string LastName;
string FirstName;
string Ocupation;
string UserName;
string EmailAdd;
string HomeAddress;
string TeleNum;
string HomeDirectory;
string RoamingProfile;
string Street;
string City;
string State;
string Zipcode;
string YnRoaming;
//macro definitions for max variable length
#define MAX_NAME_LENGTH 50
#define MAX_ADDRESS_LENGTH 100
#define MAX_ABOUT_LENGTH 200
int main()
{
char name[MAX_NAME_LENGTH], address[MAX_ADDRESS_LENGTH],
about[MAX_ABOUT_LENGTH];
//Gets The Accounts Personal Information: Ocupation, Full Name, Age, Email, Home Address, Telephone Number, UserName, HomeDirectory, RoamingProfile,
cout << "Please enter your Ocupation: " << "\n";
getline(cin, Ocupation);
cout << "Enter Your First Name and Last name: " << "\n";
cin >> FirstName >> LastName;
cout << "Enter Your Age: " << "\n";
cin >> AccountAge;
cout << "Please enter your Email: " << "\n";
cin >> EmailAdd;
cout << "Please Enter Your Home Address( ex: 123(enter) Street( Enter), City Name(Enter), State(Enter), Zipcode(Enter)): " << "\n";
cin >> HomeAddress;
cout << "Enter Street Name" << "\n";
cout << "( ex: StreetName st " << "\n";
cin >> Street;
cout << "Enter City" << "\n" ;
cin >> City;
cout << "Enter State" << "\n";
cin >> State;
cout << "Enter Zipcode" << "\n";
cin >> Zipcode;
cout << "Please Enter Your Best Telephone Number(EX:508-675-4567): " << "\n";
cin >> TeleNum;
cout << "Please Enter Your UserName: " << "\n";
cin >> UserName;
cout << "Please Enter Your Account's HomeDirectory(EX:\\HOMEDIRECTORY\\): " << "\n";
cin >> HomeDirectory;
cout << "Do you have a Roaming Profile?(Y/N)" << "\n";
cin >> YnRoaming;
if (YnRoaming == "Y") {
cout << "Please Enter Your Roaming Profile Name(IF APPLYS): " << "\n";
cin >> RoamingProfile;
}
else {
string RoamingProfile = "N / A";
}
//getline(cin, HomeAddress);
// Displays All the information entered by the user To verify it was entered correctly.
cout << "Full Name: " << LastName << "," << FirstName << ", Length: " <<
FirstName.length() + LastName.length() << "\n" << "Age: " << AccountAge << "\n"
<< "Ocupation: " << Ocupation << "\n" << "UserName: " << UserName
<< "\n" << "Email Address: " << EmailAdd << "\n"
<< FirstName << "'s Home Address" << HomeAddress << Street << City << State << Zipcode
<< "\n" << " Primary Telephone Number: " << TeleNum << "\n" << UserName << "'s Home Directory: " << HomeDirectory
<< "\n" << UserName << "'s RoamingProfile: " << RoamingProfile << "\n";
// Create File and Write to it then Close it.
ofstream MyFile("AccountInformation.txt");
MyFile << "Full Name: " << LastName << "," << FirstName << ", Length: " << FirstName.length() + LastName.length() << "\n" << "Age: " << AccountAge << "\n"
<< "Occupation: " << Ocupation << ", Length: " << Ocupation.length() << "\n" << "UserName: " << UserName << "\n" << "Email Address: " << EmailAdd << "\n" << FirstName << "'s Home Address"
<< HomeAddress << "\n" << " Primary Telephone Number: " << TeleNum << "\n" << UserName << "'s Home Directory: " << HomeDirectory << "\n"
<< UserName << "'s RoamingProfile: " << RoamingProfile << "\n";
MyFile.close();
return 0;
}
Please enter your Ocupation:
Citizens For Citizens
Enter Your First Name and Last name:
Mark Monhan
Enter Your Age:
24
Please enter your Email:
mmonhan23#gmail.com
Please Enter Your Home Address( ex: 123(enter) Street( Enter), City Name(Enter), State(Enter), Zipcode(Enter)):
524
Enter Street Name
( ex: StreetName st
Street st
Enter City
Enter State
Boston MA
Enter Zipcode
Please Enter Your Best Telephone Number(EX:508-675-4567):
02726 603-854-7845
Please Enter Your UserName:
Please Enter Your Account's HomeDirectory(EX:\HOMEDIRECTORY\):
mgede
Do you have a Roaming Profile?(Y/N)
N
Full Name: Monhan,Mark, Length: 10
Age: 24
Ocupation: Citizens For Citizens
UserName: 603-854-7845
Email Address: mmonhan23#gmail.com
Mark's Home Address524StreetstBostonMA
Primary Telephone Number: 02726
603-854-7845's Home Directory: mgede
603-854-7845's RoamingProfile:
``` ***
You need to change the line right under the cin >> EmailAdd; to be cin.ignore(); then put getline(cin, HomeAddress); that will take the whole Address and store it all in the variable HomeAddress like I want. Theres also some more changes i have implemented to make it run smoother.
every word of txt file starts on new line
ex:
first name
last name
first part of phone number
second part of phone number
first part of address
etc..
it should look like:
name
phone number
address
city, state zip
int main()
{
string username, streetAddress, city, state, phoneNum, zip;
ofstream outputFile;
outputFile.open("list.txt");
cout << "Enter your name: ";
getline(cin, username);
outputFile << username << endl;
cout << "Enter your phone number: ";
getline(cin, phoneNum);
outputFile << phoneNum << endl;
cout << "Enter street address: ";
getline(cin, streetAddress);
outputFile << streetAddress << endl;
cout << "Enter your city: ";
getline(cin, city);
outputFile << city << ", ";
cout << "Enter your state: ";
getline(cin, state);
outputFile << state << ", ";
cout << "Enter your zip code: ";
getline(cin, zip);
outputFile << zip;
outputFile.close();
ifstream inputFile;
string list;
inputFile.open("list.txt");
while (inputFile >> list) {
cout << list << endl;
}
inputFile.close();
return 0;
}
Use getline not >>
while (getline(inputFile, list)) {
cout << list << endl;
}
Your version reads a word at a time, and then outputs each word on a separate line.
I can easily create a void function to output something like a header, but I cannot get a program to read a user's input and then output it to them.
ie. Have a program say "Please enter your first name" and then output "You entered: (what they put)"
An example of what I have:
#include<iostream>
#include<conio.h>
#include<iomanip>
#include<fstream>
using namespace std;
void namefn()//namefn prototype
int main(){
string firstName,lastName;
return 0;
}
void namefn(string firstName, string lastName){
cout<<"please enter your first and last name "<<endl;
}
Use cin to read, is in iostream.
i.e.
cin >> firstName;
cout << "enter your first and last name:";
cin >> firstName >> lastName;
cout << firstName << " " << lastName;
if you want the program to display the first name and last name separately then this:
cout << "enter you first name:";
cin >> firstName;
cout << firstName << endl;
cout << "Enter your last name:";
cin >> lastName;
cout << lastName << endl;
Try this:
#include <iostream>
#include <string>
void displayFirstAndLast(const std::string& firstName, const std::string& lastName)
{
std::cout << "You are " << firstName << " " << lastName << std::endl;
}
int main(){
std::string firstName;
std::string lastName;
std::cout << "Please enter your first and last name " << std::endl;
std::cin >> firstName >> lastName;
displayFirstAndLast(firstName, lastName);
return 0;
}
I think, that you want something like this.
Or with something like "header"
#include <iostream>
#include <string>
void displayFirstAndLast(const std::string& firstName, const std::string& lastName);
int main(){
std::string firstName;
std::string lastName;
std::cout << "Please enter your first and last name " << std::endl;
std::cin >> firstName >> lastName;
displayFirstAndLast(firstName, lastName);
return 0;
}
void displayFirstAndLast(const std::string& firstName, const std::string& lastName)
{
std::cout << "You are " << firstName << " " << lastName << std::endl;
}
I'm currently taking an online C++ class and our current project requires us to read a file, take each student and put it into a vector.
My current problem is splitting the name read and setting it to the right variables.
The professor's pseudo code here:
inputFile.open(sFileName.c_str ());
while(inputFile.fail())
{
cout ERROR OPENING FILE
cout PLEASE REENTER THE PASSWORD OF THE FILE
getline(cin >> wd, sFileName);
inputFile.open(sFileName.c_str());
}
inputFile.clear();
inputFile.seek(0, ios::beg);
while(getline(inputFile, sTemp))
{
istringstream inputSStream(sTemp)
inputSStream >> sFirstName >> sMiddleName >> sLastName >> sID >> sClass;
if(sMiddleName != "|")
sFullName = sFirst name + " " + sMiddleName +" " + sLastName;
else
sFullName = sFirstName + " " + sLastName;
My current code here:
ifstream myFile;
string firstName, middleName, lastName, fullName, studentID, cID;
string inFileName, stringTemp;
cout << "Please enter the name of the file that you want to read in. \n";
cin >> inFileName;
myFile.open(inFileName);
while (myFile.fail())
{
cout << "\n""";
cout << "Error file, Please re-enter file. \n ";
cin >> inFileName;
myFile.open(inFileName);
}
myFile.clear();
myFile.seekg(0, ios::beg);
while (getline(myFile, stringTemp))
{
istringstream inputStream(stringTemp);
inputStream >> firstName >> middleName >> lastName >> studentID >> cID;
if (middleName != "|")
fullName = firstName + " " + middleName + " " + lastName;
else
fullName = firstName + " " + lastName;
//Checking what the input values are
cout << "First name is " << firstName << endl;
cout << "Middle name name is " << middleName << endl;
cout << "Last name is " << lastName << endl;
cout << "studentID is " << studentID << endl;
cout << "CID is " << cID << endl;
Student thisStudent(fullName, studentID, cID);
studentList.push_back(thisStudent);
}
myFile.close();
The current problem is that the line isn't split correctly, first name gets the whole line and mid and last name, studentID and cID all remain empty.
Here is the current file that I'm reading in:
ERIC,ANTHONY,TURNER,1234573,CISC_198
GABRIEL,FEIJO,LOPES,1234574,CISC_199
GEOFFERY,BRYAN,RANSOM,1234575,CISC_200
HANNAH,MAE ,LONGRIE,1234576,CISC_201
HASSAN,ISMAIL,AHMED,1234577,CISC_202
HUNG,B,PHAM,1234578,CISC_203
HUSSEIN,FOUAD,ALJANABI,1234579,CISC_204
JING,XUN,CHEN,1234580,CISC_205
KAJALBEN,CHIMANLAL,MAKWANA,1234581,CISC_206
DANDREA,SHAMAICAH,BUSH,1234570,CISC_195
DANIELLE,MARIE,CORTEZ,1234571,CISC_196
ERDI,T,KIDANE,1234572,CISC_197
AARON,FABIAN,LINGAD,1234567,CISC_192
AARON,T,PATCHIN,1234568,CISC_193
ALI,FOUAD,ALJANABI,1234569,CISC_194
NATHAN,|,NANN,1234585,CISC_210
NEIL,ANDREAS,FRANKA,1234586,CISC_211
OBONE,|,ORIYAVONG,1234587,CISC_212
OLIVIA,JOANNE,MAILANDER,1234588,CISC_213
RALEIGH,|,COSGROVE,1234589,CISC_214
RYAN,PAREDES,PALMARES,1234590,CISC_215
MICHAEL,DUONG,NGUYEN,1234583,CISC_208
MIGLENA,|,CHEMELEKOVA,1234584,CISC_209
STEPHEN,MICHAEL,HOUSE,1234591,CISC_216
MARCUS,D,BUTLER,1234582,CISC_207
Here is the output that I do not understand how to fix.
First name is ERIC,ANTHONY,TURNER,1234573,CISC_198
Middle name name is
Last name is
studentID is
CID is
When you read with operator >> you are splitting on whitespace. Despite the name, getline() can split by other characters than newline:
getline(inputStream, firstName, ',');
getline(inputStream, middleName, ',');
// ...
I'm writing a simple program to enter student records and store them in a coma delimited file. Everything looks good but when I run the program I get an error:
Error 1 error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>' c:\program files\microsoft visual studio 10.0\vc\include\fstream 1116 1 project1
Here's the code:
#include <cstring>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void closeOrNewRecordMenu(string enterAnotherRecord)
{
if (enterAnotherRecord == "Q" && enterAnotherRecord == "q")
{
exit(0);
}
}
void newStudentRecord(double studentNumber, string firstName, string lastName, string campus, string course1, string course2, string course3, string seniorPracticum, ofstream writeToRecordsFile)
{
int campusChoice;
do {
cout << "Student's six digit number: (Numeric only)";
cin >> studentNumber;
cin.ignore();
}
while (studentNumber < 100000 && studentNumber > 999999);
cout << "Student's first name: " << "\n";
cin >> firstName;
cin.ignore();
cout << "Student's last name: " << "\n";
cin >> lastName;
cin.ignore();
while (campusChoice < 1 || campusChoice > 3)
cout << "Which campus will " << firstName << " " << lastName << " be attending class at: " << "\n";
cout << "For the North campus enter 1" << "\n";
cout << "For the South campus enter 2" << "\n";
cout << "For the Seaside campus enter 3" << "\n";
cin >> campusChoice;
cin.ignore();
if (campusChoice == 1)
{
campus = "North Campus";
}
else if (campusChoice == 2)
{
campus = "South Campus";
}
else if (campusChoice == 3)
{
campus = "Seaside Campus";
}
else {
cout << "Please enter a valid choice." << "\n" << "\n";
}
cout << "Student's first course: " << "\n";
getline (cin, course1);
cin.ignore();
cout << "Student's second course: " << "\n";
getline (cin, course2);
cin.ignore();
cout << "Student's third course: " << "\n";
getline (cin, course3);
cin.ignore();
do {
cout << "Is " << firstName << " " << lastName << " a senior this year? Please enter \"Y\" for yes and \"N\" for no." << "\n";
cin >> seniorPracticum;
cin.ignore();
} while (seniorPracticum != "y" && seniorPracticum != "Y" && seniorPracticum != "n" && seniorPracticum != "N");
writeToRecordsFile << studentNumber << "," << firstName << "," << lastName << "," << campus << "," << course1 << "," << course2 << "," << course3 << "," << seniorPracticum << "\n";
cout << "The student record for " << firstName << " " << lastName << " has been saved." << "\n" << "\n";
}
int main()
{
cout << "Hello there! Welcome to the student record manager. From here you can enter new student information and save it to a file!!!! (More exciting to the developer than the user)." << "\n" << "\n";
string enterAnotherRecord;
ofstream writeToRecordsFile;
writeToRecordsFile.open("cop2224_proj1.txt");
while (enterAnotherRecord != "Q" && enterAnotherRecord != "q") {
cout << "Press \"N\" to create a new student record or press \"Q\" to quit." << "\n" << "\n";
cin >> enterAnotherRecord;
closeOrNewRecordMenu(enterAnotherRecord);
string firstName, lastName, seniorPracticum, campus, course1, course2, course3;
double studentNumber;
newStudentRecord(studentNumber, firstName, lastName, campus, course1, course2, course3, seniorPracticum, writeToRecordsFile);
}
writeToRecordsFile.close();
}
Streams are not copyable, and even if they were, you wouldn't want to do so here – pass by reference instead. Change your newStudentRecord signature to:
void newStudentRecord(double studentNumber, string firstName, string lastName, string campus, string course1, string course2, string course3, string seniorPracticum, ofstream& writeToRecordsFile);
That being said, why are you passing in all those arguments when you don't care about their initial values and you don't use them as output parameters? Simplify your signature to the following:
void newStudentRecord(ofstream& writeToRecordsFile);
and declare the other arguments as local variables inside of newStudentRecord.
As an aside, you're reading campusChoice before initializing it, which will yield undefined behavior.