The task is as follows:
Create an ASCII text and a C++ program to read it. Print the Shipped date, part number, first name, last name, company name from the ASCII text.
I had to create my own ASCII text. I tested it, and was able to read it successfully. Now, I'm having trouble reading character by character and sending to an array so that I can filter out the data I don't want to display. I will show my ASCII text file followed by the code I'm using to read it.
04/12/11 D50625 74444 James Lehoff Rotech
04/12/11 D60752 75255 Janet Lezar Rotech
04/12/11 D40295 74477 Bill McHenry Rotech
04/12/11 D23745 74470 Diane Kaiser Rotech
04/12/11 D50892 75155 Helen Richardson NapTime
(I don't know why this format won't work...sorry...its not important for the task)
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
//initialize array
const int MAXROWS = 5;
const int MAXCOLS = 64;
int ship_array [MAXROWS][MAXCOLS];
int row,col;
string filename = "/Users/Jimmy/Desktop/shipped.txt";
string line;
ifstream inFile;
inFile.open(filename.c_str()); //opens ASCII file
if (inFile.fail()) //checks for successful open
{
cout << "\nThefile was not successfully opened"
<< "\n Please check that the file currently exists." << endl;
exit(1);
}
cout << "\nThe file has been successfully opened for reading.\n" << endl;
///////////code to read and output the data will go here///////////////////
cout << "Shipped Date Part Number First name Last Name Company Name";
//cycle through rows and columns//
row=0;
while(row<MAXROWS)
{
for (col=1; col<9; col++) // STORE SHIPPED DATE
{
ship_array[row][col] = get(filename.c_str());
cout << ship_array[row][col]; //DISPLAY SHIPPED DATE
}
for (col=22; col<27; col++) //STORE PART NUMBER
{
ship_array[row][col] = get(filename.c_str());
cout << ship_array[row][col]; //DISPLAY PART NUMBER
}
for (col=31; col<36; col++) // STORE FIRST NAME
{
ship_array[row][col] = get(filename.c_str());
cout << ship_array[row][col]; //DISPLAY FIRST NAME
}
for (col=39; col< 49; col++) // STORE LAST NAME
{
ship_array[row][col] = get(filename.c_str());
cout << ship_array[row][col]; //DISPLAY LAST NAME
}
for (col=51; col<65; col++) // STORE COMPANY NAME
{
ship_array[row][col] = get(filename.c_str());
cout << ship_array[row][col]; //DISPLAY COMPANY NAME
}
}
inFile.close();
return 0;
}
I KNOW the error is where I'm storing my values FROM the ASCII text to my array. I thought get() was for reading one character at a time but it doesn't work. Please point me in the right direction.
EDIT
I changed my code a bit. I tried something new. This gave me a few zeros. I didn't even bother going further down. My variables and initializations aren't right and I don't know why.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include <string>
using namespace std;
int main()
{
//initialize array
const int MAXROWS = 5;
const int MAXCOLS = 64;
int ship_array [MAXROWS][MAXCOLS];
int row,col;
//initialize input stream
string ascii_data = "/Users/Jimmy/Desktop/shipped.txt";
ifstream data;
stringstream ss(ascii_data);
data.open(ascii_data.c_str()); //opens ASCII file
if (data.fail()) //checks for successful open
{
cout << "\nThefile was not successfully opened"
<< "\n Please check that the file currently exists." << endl;
exit(1);
}
cout << "\nThe file has been successfully opened for reading.\n" << endl;
cout << "Shipped Date Part Number First name Last Name Company Name" << endl;
//cycle through rows and columns//
row=0;
while(row<MAXROWS)
{
for (col=1; col<9; col++) // STORE SHIPPED DATE
{
ss >> ship_array[0][col];
cout << ship_array[row][col];//DISPLAY SHIPPED DATE
}
for (col=22; col<27; col++) //STORE PART NUMBER
{
ss >> ship_array[row][col]; //DISPLAY PART NUMBER
}
for (col=31; col<36; col++) // STORE FIRST NAME
{
ss >> ship_array[row][col]; //DISPLAY FIRST NAME
}
for (col=39; col< 49; col++) // STORE LAST NAME
{
ss >> ship_array[row][col]; //DISPLAY LAST NAME
}
for (col=51; col<65; col++) // STORE COMPANY NAME
{
ss >> ship_array[row][col]; //DISPLAY COMPANY NAME
}
row++;
}
data.close();
return 0;
}
Related
I wrote a code to populate an array from a file
and then use that array to compare it with the user input
The program should ask the user to enter a name or partial name to search for in the
array
here is the code:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
bool found = false;
const int arraySize = 35;
const int length = 100;
char contacts[arraySize][length];
int count = 0; // Loop counter variable
ifstream inputFile; // Input file stream object
inputFile.open("input.txt"); // Open the file.
// Read the numbers from the file into the array.
// After this loop executes, the count variable will hold
// the number of values that were stored in the array.
while (count < arraySize && inputFile >> contacts[count])
count++;
// Close the file.
inputFile.close();
char search[length];
char *fileContact = nullptr;
int index;
cout << "To search for your contact's number \nplease enter a name or partial name of the person.\n";
cin.getline(search, length);
for (index = 0; index < arraySize; index++)
{
fileContact = strstr(contacts[index], search);
if (fileContact != nullptr)
{
cout << contacts[index] << endl;
found = true;
}
}
if (!found) cout << "Sorry, No matches were found!";
return 0;
}
and the names in the file are
"Alejandra Cruz, 555-1223"
"Joe Looney, 555-0097"
"Geri Palmer, 555-8787"
"Li Chen, 555-1212"
"Holly Gaddis, 555-8878"
"Sam Wiggins, 555-0998"
"Bob Kain, 555-8712"
"Tim Haynes, 555-7676"
"Warren Gaddis, 555-9037"
"Jean James, 555-4939"
"Ron Palmer, 555-2783"
so the code works, but the problem is
when I write Alejandra for example
the output is: "Alejandra
the output is supposed to show the full name and the number:
"Alejandra Cruz, 555-1223"
does anyone know how to fix this?
thanks!!
When you use
inputFile >> contacts[count]
Leading whitespace characters are discarded.
Non-whitespace characters are read into contants[count].
Reading stops when a whitespace character is encountered.
That explains your output.
You need to use istream::get instead.
while (count < arraySize && inputFile.get(contacts[count], length) )
count++;
In response to OP's comment
The above should all the lines of the file up to arraySize number of lines.
You could add some debugging output to troubleshoot the problem.
while (count < arraySize && inputFile.get(contacts[count], length) )
{
std::cout << "Read " << count+1 << "-th line.\n" << "\t" << contants[count] << "\n";
count++;
}
Write a simple telephone directory program in C++ that looks up phone numbers in a file containing a list of names and phone numbers. The user should be prompted to enter a first name and last name, and the program then outputs the corresponding number, or indicates that the name isn't in the directory. After each lookup, the program should ask the user whether they want to look up another number, and then either repeat the process or exit the program. The data on the file should be organized so that each line contains a first name, a last name, and a phone number, separated by blanks. You can return to the beginning of the file by closing it an opening it again.
I cant get the line
check = strstr(phoneDirectory, name);
to work strstr part keep giving the error: no instance of overloaded function "strstr" matches the argument list argument types.
Here a copy of my code:
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
int arraySize();
int main()
{
const int SIZE = arraySize();
char *phoneDirectory;
int size=0;
char name; //name to look for
char *check = NULL;
bool find = false;
phoneDirectory = new char [SIZE];
ifstream phoneNumbers;
phoneNumbers.open("phoneNumbers.txt");
if (!phoneNumbers)
cout << "Error opening data file\n";
//looping throught the name file
else
{
for (int i = 0; i < SIZE; i++)
{
phoneNumbers >> phoneDirectory;
}
phoneNumbers.close(); //closes data file
}
phoneNumbers.close();
// Get a name or partial name to search for.
cout << "Enter a name or partial name to search for: ";
cin.getline(phoneDirectory, name);
cout << "\nHere are the results of the search: " << endl;
int entries = 0;
for (int i = 0; i < size; i++)
{
check = strstr(phoneDirectory, name);
if (check != NULL)
find = true;
}
if (!find)
cout << "No matches!" << endl;
delete [] phoneDirectory;
return 0;
}
int arraySize()
{
string phoneNum;
int size = 0;
ifstream phoneNumbers; // Input file stream object
// Open the data file.
phoneNumbers.open("phoneNumbers.txt");
if (!phoneNumbers)
cout << "Error opening data file\n";
//looping throught the name file
else
{
while (getline(phoneNumbers, phoneNum))
{
size++;
}
phoneNumbers.close(); //closes data file
}
return size;
}
Your name variable is a char. Should it be a char* instead?
I created a script to take data from a text file and graph it in Root (CERN) but haven't used root in about a year, updated to the current version of Root and now it gets the error "Error: Function readprn() is not defined in current scope :0:
* Interpreter error recovered *" when i try to use it with Root.
It runs an excel data file that I saved as a txt file. The first column is the x value corresponding to each y value in the subsequent 768 columns. At the end it graphs and fits and loops over a couple graphs.
I'm mostly wondering if there is anything in the new versions that would cause this to not be able to be read by root.
#include <TGraph.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TMath.h>
#include <TStyle.h>
#include <iostream>
#include <fstream>
#include <string>
using std::cout; using std::endl;
int threshold1(Int_t channel=0)
{
const char* ifname = "thresholdScanRun110FPGA4.txt";
cout<< "processing file " << ifname <<endl;
std::ifstream ifile(ifname);
if (!ifile) {
cout<< "Could not find file " << ifname <<endl;
return 0;
}
//std::string line;
// discard the first two lines
//std::getline(ifile, line);
//cout<< line <<endl;
//std::getline(ifile, line);
//cout<< line <<endl;
std::string str;
double number;
// read the first row (in sense of Exel's row)
ifile >> str;
//cout<< str <<endl;
for (int i=0; i<768; ++i) {
ifile >> number;
//cout<< number << " ";
}
//cout<<endl;
// read the second "row"
ifile >> str;
//cout<< str <<endl;
for (int i=0; i<768; ++i) {
ifile >> number;
//cout<< number << " ";
}
//cout<<endl;
double thres[60];
double prob[60][768];
int nthres_max = 60;
for (int ithres=0; ithres<nthres_max; ++ithres) {
ifile >> thres[ithres];
for (int iprob=0; iprob<768; ++iprob) ifile >> prob[ithres][iprob];
}
cout<< "The channel " << channel <<endl;
for (int ithres=0; ithres<60; ++ithres) {
cout<< thres[ithres] << " " << prob[ithres][channel] <<endl;
}
Double_t probability[60];
for (int ithres=0; ithres<60; ++ithres) probability[ithres] = prob[ithres][channel];
TGraph* gr = new TGraph(60, thres, probability);
gr->SetMarkerStyle(29);
gr->SetMarkerColor(4);
gr->SetTitle("Threshold Scan ChipX, ChanY");
TF1* ferfc = new TF1("ferfc", "0.5*TMath::Erfc((x-[0])/[1])", 0, 767);
ferfc->SetParameters(100,10);
new TCanvas;
gStyle->SetOptFit(1);
gr->Draw("apl");
gr->Fit("ferfc");
return 0;
}
int threshold_all()
{
for (Int_t channel=0; channel<2; ++channel) {
threshold1(channel);
}
}
when loading your macro in root 6.07/04, with .L macro.C I receive the following warning:
/tmp/tmp.rQTNVdlydv/macro.C:88:1: error: control reaches end of non-void function [-Werror,-Wreturn-type]
which is because you don't have a return statement in int threshold_all(). Fixing this the macro seems fine to me. (runs, opens a canvas, some fit output. Since I don't have your input values, I just created a text file with a few invented numbers and reduced the number of thresholds and values to 5x6. Which is why I'm not concerned about the abnormal fit termination which I receive.).
Also loading the macro with compilation .L macro.C+ looks fine to me once adding the return statement.
Reading from file and Min/max logic.
As more info comes in, I will update my question, statements, and code every 30 minutes so I don't edit faster than some can answer.
My question is, how do I set the program to read one name at a time and not concatenate the names?
The file is a .txt file, and reads:
Jackie Sam Tom Bill Mary Paul Zev Barb John
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// File stream objects
ifstream inputFile;
inputFile.open("LineUp.txt");
// Non-user variables
string first_In_Line = "",
last_In_Line = "",
previous_Name = "",
next_name = "";
if (inputFile)
{
// Display message to user
cout << "Reading file... \n";
while (inputFile >> next_name)
{
cout << next_name;
if (next_name > last_In_Line)
{
first_In_Line = last_In_Line;
last_In_Line = next_name;
}
else if (next_name < first_In_Line)
{
last_In_Line = first_In_Line;
first_In_Line = next_name;
}
// This else clause should only apply to the first iteration
else
{
first_In_Line = next_name;
}
}
//Close the file
inputFile.close();
// Display first in line and last in line
cout << first_In_Line << " is first in line." << endl;
cout << "And " << last_In_Line << " is last in line." << endl;
}
else
{
// Display error message.
cout << "Error opening the file.\n";
}
return 0;
}
Output is:
Reading file...
JackieSamTomBillMaryPaulZevBarbJohnJohn is first in line.
And Sam is last in line.
What I am proposing to you is to use array then use the algorithm sort function
Array is a data structure which is use to save data while the program is running.
Therefore we could save those data from the file to that array. the name of the array is dataFromFile that could save up to 9 string values. so if you have more names in your file just update the size of the array or use vector
ifstream file("dataToRead.txt");
string dataFromFile[9];
string line;
int index = 0;
if(!file)
{
cout<<"cannot find this file" <<endl;
}
else
{
if(file.is_open())
{
while (getline(file,line))
{
dataFromFile[index] = line;
index++;
}
file.close();
}
}
Then display what we have inside of the array using a loop
for(int j=0;j<9;j++)
{
// to do display
cout<<dataFromFile[j] <<endl;
}
NOW to sort them just #include <algorithm> then use the sort method on the array which is called dataFromFile
sort(begin(dataFromFile),end(dataFromFile));
Then redisplayed what you have into the array
for(int j= 0 ;j < 9;j++)
{
// after sorting
cout<<dataFromFile[j] <<endl;
}
Without using arrays, which is the best solution, there was a logic error in if-statements.
First, strings were initialized as empty, so empty strings were always sorted as first_In_Line. first_In_Line needed assigned a value on the first iteration of the while-loop.
Next, by the fourth iteration of the while loop, the variables became illogically assigned, and "Sam" was passed back and forth between first_In_Line and last_In_Line through the rest of the while-loop.
Here's how I solved this problem:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// File stream objects
ifstream inputFile;
inputFile.open("LineUp.txt");
// Non-user variables
string first_In_Line = "",
last_In_Line = "",
next_name = "";
if (inputFile)
{
// Display message to user
cout << "Reading file... \n\n";
while (inputFile >> next_name)
{
cout << next_name << endl; // list the names
if (last_In_Line == first_In_Line)
{
first_In_Line = next_name;
}
else if (next_name > last_In_Line)
{
last_In_Line = next_name;
}
else if (next_name < first_In_Line)
{
first_In_Line = next_name;
}
}
//Close the file
inputFile.close();
// Display first in line and last in line
cout << endl << first_In_Line << " is first in line." << endl;
cout << "And " << last_In_Line << " is last in line." << endl;
}
else
{
// Display error message.
cout << "Error opening the file.\n";
}
return 0;
}
How can I add more than one string or user input to an array? I am trying to create a contact book that requires the user to add up to 10 contacts. I am trying to store them an an array or a txt file and then later I want to be able to use this input.
Here is my code. If what I'm trying to say is not clear, running the code will help.
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
// declare two variables;
char name[20];
int age;
string ans;
do {
// get user to input these;
cout << "What is your name: ";
cin >> name;
cout << "What is your age : ";
cin >> age;
cout<<"continue ";cin>>ans;
}while((ans == "y" || ans=="yes"));
// create output stream object for new file and call it fout
// use this to output data to the file "test.txt"
char filename[] = "test.txt";
ofstream fout(filename);
fout << name << "," << age << "\n"; // name, age to file
fout.close(); // close file
// output name and age : as originally entered
cout << "\n--------------------------------------------------------"
<< "\n name and age data as entered";
cout << "\n Your name is: " << name;
cout << "\n and your age is: " << age;
// output name and age : as taken from file
// first display the header
cout << "\n--------------------------------------------------------"
<< "\n name and age data from file"
<< "\n--------------------------------------------------------";
ifstream fin(filename);
char line[50];
fin.getline(line, 50);
char fname[20];
int count = 0;
do
{
fname[count] = line[count];
count++;
}
while (line[count] != ',');
fname[count] = '\0';
count++;
char fage_ch[10];
int fage_count = 0;
do
{
fage_ch[fage_count] = line[count];
fage_count++; count++;
}
while (line[count] != '\0');
fage_ch[fage_count] = '\0';
int fage_int = 0;
int total = 0;
char temp;
for (int i = 0; i < (fage_count); i++)
{
temp = fage_ch[i];
total = 10*total + atoi(&temp);
}
fage_int = total;
// display data
cout << "\n\n Your name is: " << fname;
cout << "\n and your age is: " << fage_int;
cout << "\n\n--------------------------------------------------------";
cout <<endl;
return EXIT_SUCCESS;
}
You would probably be better off using an array of structs instead of two seperate arrays to store the name & age for each entry. Then you can just loop through using strcpy to copy the input string from name into your struct's name. If you aren't comfortable with structs you could also use a couple of 2 dimensional arrays.
This looks like a homework assignment so I'm not going to post code, but for a basic algorithm to get you started (and hopefully simplify what you've got):
#define MAX_CONTACTS 10
#define MAX_NAME_LENGTH 20
// 2D array to store up to 10 names of max 20 character length
char nameVar[MAX_CONTACTS][MAX_NAME_LENGTH]
int ageVar[MAX_CONTACTS]
do until end of user input
read name into nameVar[index]
read age into ageVar[index]
index += 1
end loop
while contactCounter < index
ouput nameVar[contactCounter]
output age[contactCounter]
// you could also write to file in this loop if thats what you're trying to do
// using the fprintf function to write to an opened file
contactCounter += 1
end loop
Also, I'm not sure what you're trying to do with that atoi call, but it looks like it shouldn't be necessary. How atoi works is that it looks at the first character it is passed and it converts all of the digits until it encounters a non-digit character in the array. So if you have the char array c="123h" atoi would return 123. If you pass atoi "1h2" it will return 1.
Also you can use fprintf to print out both a char array and an int to a file.
So if you've got int i and char s[10] = "hello" and file stream you could print to stream like:
fprintf(stream, "my text to display: %s %i", s,i)
I hope that helps.