This seems like it should be easy, which is why it is driving me especially insane. Hopefully someone out there will see the problem right off. I'm just trying to build arrays from an array built from a user input. It seems to create an array that is bigger than the one I meant for it to. Here's the program:
int main()
{
ifstream inFile;
ofstream outFile;
int numReq, fileSize;
string lang, dash;
char fileName[40];
char confirm[10];
char confirm2[10];
int character;
char year[3];
char month[1];
char day[1];
char hour[1];
cout << "What file to process?" << endl;
cin >> fileName;
year[0] = fileName[14];
year[1] = fileName[15];
year[2] = fileName[16];
year[3] = fileName[17];
cout << "year = " << year << "." << endl;
month[0] = fileName[18];
month[1] = fileName[19];
cout << "month = " << month << "." << endl;
cout << "so I gotta know, what is..." << endl;
cout << "month[0]? " << month[0] << endl;
cout << "month[1]? " << month[1] << endl;
cout << "month[2]? " << month[2] << endl;
cout << "month[3]? " << month[3] << endl;
cout << "month[4]? " << month[4] << endl;
cout << "month[5]? " << month[5] << endl;
cout << "month[6]? " << month[6] << endl;
day[0] = fileName[20];
day[1] = fileName[21];
cout << "day = " << day << "." << endl;
hour[0] = fileName[23];
hour[1] = fileName[24];
cout << "hour = " << hour << "." << endl;
cout << "so, 'fileName[23]' is = " << fileName[23] << "?" << endl;
cin >> confirm;
cout << "So, the year is " << year << ", the month is " << month
<< ", the day is " << day << ", the hour is " << hour << "?" << endl;
cin >> confirm;
//cout << "Is this what you chose? " << fileName << endl;
//cin >> confirm;
//cout << "Which character to manipulate?" << endl;
//cin >> character;
//cout << "This one? " << fileName[character] << endl;
//cin >> confirm2;
inFile.open(fileName);
assert (!inFile.fail());
outFile.open("revisedPracticeFile1.txt");
outFile << fixed << showpoint; // I have no idea what this is...
outFile << setprecision(2); // .. or this for that matter.
cout << "Processing data" << endl;
inFile >> lang;
while (!inFile.eof() ){
if (lang.length() <= 2){
outFile << lang << " ";
// I should keep in mind, that, for whatever reason, it seemed like the
//item 'setw(6)' made the program work when I put it in, but didn't seem
//to make the program stop working when I took it out. Curious..
inFile >> dash >> numReq >> fileSize;
outFile << numReq << " " << fileSize << endl;
}
else{
inFile >> dash >> numReq >> fileSize;
cout << "took out " << lang << " " << numReq << " " << fileSize << endl;
}
inFile >> lang;
}
inFile.close();
//assert(!inFile.fail());
outFile.close();
return 0;
}
...And, this is what happens when I run the program:
What file to process?
projectcounts-20090101-010000
year = 2009.
month = 01009.
so I gotta know, what is...
month[0]? 0
month[1]? 1
month[2]? 0
month[3]? 0
month[4]? 9
month[5]?
month[6]?
day = 011009.
hour = 0111009.
so, 'fileName[23]' is = 0?
yes
So, the year is 1009, the month is 11009, the day is 111009, the hour is 0111009?
^C
... So what gives?
The syntax char year[3]; declares an array with 3 element. But, then you use it to store 4 elements. There are similar issues with your other arrays.
Also, you're using char arrays as strings. That's a C (not C++) way to do things. Of course you're allowed to do this if you want. But, these c-style strings use the convention that the last item is a zero.
Thus, if you wanted a C-style string to store the work 'foo', you could do it like this
char string[10]; // anything bigger than 3 works
string[0] = 'f';
string[1] = 'o';
string[2] = 'o';
string[3] = '\0'; // this zero tells functions like `printf` that the string has ended.
Without that last zero, functions like printf will just keep outputting memory locations until it happens upon a zero somewhere.
EDIT: Consider using c++ std::string for your string processing.
Related
How should I edit the specific line in a text file? And how should I avoid overwriting issue. ( How do I keep the record I had added before instead of replacing them by the new records?)
I tried to use line.replace but it says " No matching member function for call to replace ".
else if(choice == 4){
// count++;
string edit;
string newdate;
double newincome;
double newoutcome;
double EditTodayBalance = 0;
string emptySpace = " ";
// string sentence;
cout << " There are " << count << " record(s) in the file " << endl;
cout << " Please enter the date to edit " << endl;
cin >> edit;
size_t pos;
ifstream Record("BankRecord.txt");
if (Record.is_open()) {
while (getline(Record, line)) {
pos = line.find(edit);
if (pos != string::npos) // string::npos is returned if
string is not found
{
cout << line << endl;
cout << " Enter what you want to replace " << endl;
cout << " Please enter the new date you want to put " << endl;
cin >> newdate;
cout << " Please enter the new income you want to put " << endl;
cin >> newincome;
cout << " Please enter the new outcome you want to put " << endl;
cin >> newoutcome;
cout << " Your new Record is " << endl;
cout << count << emptySpace << newdate << emptySpace << newincome << emptySpace << newoutcome << endl;
//line.replace()
}
}
}
EditTodayBalance = newincome - newoutcome;
cout << " Today's balance is " << EditTodayBalance << endl;
cout << " Please reenter your choice " << endl;
cin >> choice;
}
I expect if the old line is " 1 2/2/2019 32 21 " and I input the new line to be " 1 2/3/2019 22 11 ". Then when I open the file the record will be the new one.
I'm afraid you will have to re-write the entire file. Read the content of the file line by line, store it in memory (maybe a vector of strings). Now do your editing on the specified line in that vector. When the operation is complete, dump the entire content of vector in another file. You may later replace the original file.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...
Doing an assignment and struggling hard. I think I've narrowed down my problem to the for loop. Can anyone explain how to fix this? I can't find an answer on google or here that's helping me get it. I have to make an array of some data files I was given. Then use a for loop to display the results. The input is:
1/8/2016,98.550003,96.959999,70798000
1/11/2016,98.970001,98.529999,49739400
1/12/2016,100.550003,99.959999,49154200
etc.
The expected output should be clean numbers like above.
The observed output is a mess of numbers that's way too big.
//Variable Declaration
const int SIZE = 400;
double stockOpen[SIZE];
double stockClose[SIZE];
double stkCloseAVG=0;
double minStkClose;
double maxStkClose;
int stockVolume[SIZE];
int i = 0;
string name = "r";
string stockDate[SIZE];
string stockName;
string filename;
ifstream in;
string stkDate, stkOpen, stkClose, stkVol;
int actSize;
cout << "Welcome to " << name << "'s stock majigger thingy!" << endl;
cout << "Please enter the stock name (aapl; spy)" << endl;
cin >> stockName;
filename = stockName + ".table.csv";
in.open(filename.c_str());
if (!in)
{
cout << "File Error! Please try again! I BELIEVE IN YOU, LOVE!" << endl;
system("pause");
exit(-1);
}
while (!(in.eof()) && i < SIZE)
{
getline(in, stkDate, ',');
getline(in, stkOpen, ',');
getline(in, stkClose, ',');
getline(in, stkVol, '\n');
i++;
// Check:cout << stkDate << endl <<endl<< stkOpen<<endl << stkClose<<endl << stkVol;
//system("pause");
}
actSize = i;
//system("clr");
for (int i=0; i < actSize; i++) // <- Need help here
{
cout << "Stock Daily Performance Report -" << stockName << endl;
cout << setw(10) << "Date" << setw(7) << "Open" << setw(7) << "Close" << setw(11) << "Volume" << endl;
cout << setw(10) << stockDate[i] << fixed << setprecision(2) << setw(7) << stockOpen[i] << setw(7) << stockClose[i] << fixed << setprecision(0) << setw(11) << stockVolume[i] << endl;
stkCloseAVG= stkCloseAVG + stockClose[i];
minStkClose = stockClose[1];
maxStkClose = stockClose[1];
if (stockClose[i] < minStkClose)
minStkClose = stockClose[i];
if (stockClose[i] > maxStkClose)
maxStkClose = stockClose[i];
}
cout << "Stock Price" << endl;
cout << endl;
cout << "Average" << setw(5) << stkCloseAVG << endl;
cout << "Minimum" << setw(5) << minStkClose << endl;
cout << "Maximum" << setw(5) << maxStkClose << endl;
system("pause");
return 0;
Hi I want to use the same letter for an int and cin keyboard input so when I enter in the new number it changes the number in the cell when I enter the score in with the keyboard sample code take into account i'm still a beginner and still learning:
int h = 0;
cout << " _______________________" << endl;
cout << "|chelsea fc |"<< h << "|" << endl;
cout << "|___________|__________|" << endl;
string h = "";
cout << "Type here to add score to table" << endl;
getline(cin, h);
cout << "You added the score " << h << " to the table" << endl;
If I understand you correctly, you want something like this:
int score = 0;
cout << " _______________________" << endl;
cout << "|chelsea fc |"<< score << "|" << endl;
cout << "|___________|__________|" << endl;
cout << "Type here to add score to table" << endl;
cin >> score;
cout << "You added the score " << score << " to the table" << endl;
Remember that when reading numbers and strings, using the input operator >> reads and discards leading white-space in the input, so even if there is a newline in the input buffer after the input of the score, if you attempt to read a new number or a string that newline will simply be ignored.
Try to write a function that outputs the score table based on an integer. Something like this:
void write_table(int h) {
cout << " _______________________" << endl;
cout << "|chelsea fc |"<< h << "|" << endl;
cout << "|___________|__________|" << endl;
}
Call that function after you ask the user for input.
How do you check for non-numeric input using C++? I am using cin to read in a float value, and I want to check if non-numerical input is entered via stdin. I have tried to use scanf using the %d designator, but my output was corrupted. When using cin, I get the correct format, but when I enter, a string such as "dsffsw", I get an infinite loop.
The commented code was my attempt to capture the float, and type cast it as string, and check if it is a valid float, but the check always comes up false.
I have tried using other methods I have found on the message boards, but they want to use scanf in C and not cin in C++. How do you do this in C++? Or in C if it is not feasible.
while (!flag) {
cout << "Enter amount:" << endl;
cin >> amount;
cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl;
//if (!strtod(((const char *)&amount), NULL)) {
// cout << "This is not a float!" << endl;
// cout << "i = " << strtod(((const char *)&amount), NULL) << endl;
// //amount = 0.0;
//}
change = (int) ceil(amount * 100);
cout << "change = " << change << endl;
cout << "100s= " << change/100 << endl;
change %= 100;
cout << "25s= " << change/25 << endl;
change %= 25;
cout << "10s= " << change/10 << endl;
change %= 10;
cout << "5s= " << change/5 << endl;
change %= 5;
cout << "1s= " << change << endl;
cout << "END The amount you entered is: " << amount << endl;
}
return 0;
}
int amount;
cout << "Enter amount:" << endl;
while(!(cin >> amount)) {
string garbage;
cin.clear();
getline(cin,garbage);
cout << "Invalid amount. "
<< "Enter Numeric value for amount:" << endl;
}
I think you task relates to the so called defensive programming, one of it`s ideas is to prevent situations like one you described (function expects one type and user enters another).
I offer you to judge whether input is correct using method that returns stream state , which is good(),
so I think it will look something like this:
int amount = 0;
while (cin.good()) {
cout << "Enter amount:" << endl;
cin >> amount;