I am trying to perform some operations on a text file containing a repetition of a C based string and some numbers. My code successfully carried out the operation on the first set but it would not get to the remaining sets.
Please see the content of the text file below:
Max Scherzer 2017
6.2 4 2 2 2 7
6.0 4 3 1 2 10
mod Cameron 2018
6.4 4 1 2 1 3
6.0 4 3 5 2 8
John Brandonso 2019
6.1 1 3 5 2 7
6.5 4 7 3 4 10
I have used .eof() and it completely messed up what i am doing.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
char playername [25];
int season;
ifstream gamefilein;
gamefilein.open("C:\\Users\\troy\\Desktop\\GAME_SCORE\\gameinfo.txt");
if(!gamefilein)
{
cout<<"unable to open file";
}
double IP;
int H,R,ER,BB,K;
int counter=0;
double totalscore=0;
while(!gamefilein.fail())
{
gamefilein.get(playername,25);
gamefilein>>season;
cout<<playername<<season<<endl;
cout<<"Game Scores:"<<endl;
while(gamefilein>>IP>>H>>R>>ER>>BB>>K)
{
int IPa=IP;
int IPb=(IP-IPa)*10;
int IPc=0;
if(IPa>4)
{
IPc=IPa-4;
}
int score=50+(IPa*3)+(IPb*1)+(IPc*2)+(K*1)-(H*2)-(ER*4)-((R-ER)*2)-(BB*1);
cout<<score<<endl;
counter++;
totalscore+=score;
}
cout<<"Number of Games Started: "<<counter<<endl;
cout<<fixed<<setprecision(2)<<"Average Game Score:
<<(totalscore/counter)<<endl<<endl;
}
gamefilein.close();
return 0;
}
I get the below result, but I want the same result for the rest of the information in the text file, for example, I am expecting two more results like the one I have below.
Max Scherzer 2017
Game Scores:
63
64
Number of Games Started: 2
Average Game Score: 63.50
Aren't you reading the file as a char array?
If I read this correctly you try to shift an int and double over a char array with numbers in a STRING right?
e.g. "6.2" string is different than a 6.2 double number in your memory, hence why it cant work.
You also seem to have a lot of spaces which should not forget as well.
Where do you get that string to begin with? I would recommend you change the creation of that file to a more convenient format e.g. cv or json
I just solved my problem myself. The problem occurred when the loop operating on the integers and double completes its run and sees the character-based string that is in the next dataset. So i inserted a clear member function just at the point where i check for end of file
(gamefilein.clear())
and that solved my problem.
Thanks for attempting to help
Related
I am researching about the Balloon Sort because it was one of my assignments, but the Google give me one Balloon Sort link sample only and the rest was Bubble Sort.
I compiled the code in Dev C++ and said that it has some error...
Here's [a link] (http://www.codemiles.com/c-examples/balloon-sort-algorithm-c-implementation-code-sorting-array-t10823.html) ! That Google gave me...
here is the code...
#include<iostream>
using namespace std;
void balloon()
{ int num, N[10], x, y, z,temp;
clrscr();
cout<<"How many number would you like to sort? ";
cin>>num;
cout<<"Input the "<<num<<" numbers:"<<endl;
for(x=0;x<num;x++)
cin>>N[x];
for(x=0;x<num;x++)
{
for(y=0;y<num-x;y++)
{ if(N[x] > N[x+y])
{ temp=N[x];
N[x] =N[x+y];
N[x+y]=temp;
}
}
cout<<"pass "<<x+1<<"] ";
for(z=0;z<num;z++)
{
cout<<setw(5)<<N[z];
}
cout<<endl;
}
}
Error Picture Link
Can you help me how to code the Balloon Sort in C++ with some explanations... Thanks in advance!
It will have some error because the compiler will search the int main() so change the void balloon, and remove the clrsrc();
Since you used the setw(), you must use the #include <iomanip>
The header is part of the Input/output library of the C++ Standard Library. It defines the manipulator functions resetiosflags(), setiosflags(), setbase(), setfill(), setprecision(), and setw(). These functions may be conveniently used by C++ programs to affect the state of iostream objects.
And lastly you must make the cout<<setw(5)<<N[z]; into cout<<std::setw(5)<<N[z];
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{ int num, N[10], x, y, z,temp;
cout<<"How many number would you like to sort? ";
cin>>num;
cout<<"Input the "<<num<<" numbers:"<<endl;
for(x=0;x<num;x++)
cin>>N[x];
for(x=0;x<num;x++)
{
for(y=0;y<num-x;y++)
{ if(N[x] > N[x+y])
{ temp=N[x];
N[x] =N[x+y];
N[x+y]=temp;
}
}
cout<<"pass "<<x+1<<"] ";
for(z=0;z<num;z++)
{
cout<<std::setw(5)<<N[z];
}
cout<<endl;
}
}
and if you run it... here is my sample output
How many number would you like to sort? 5
Input the 5 numbers:
8
2
4
9
0
pass 1] 0 8 4 9 2
pass 2] 0 2 8 9 4
pass 3] 0 2 4 9 8
pass 4] 0 2 4 8 9
pass 5] 0 2 4 8 9
--------------------------------
Process exited after 8.305 seconds with return value 0
Press any key to continue . . .
Hope this works on your assignment! Good Luck!
For example, I have a file named Bjarne.txt and in it there's the integers:
16 2 3 4
I have made a program to read the integers available inside the file and output them to me in the console window , however , I'm trying to use cin.unget() and by that get understanding of what it does actually , here's the source code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream ifs("Bjarne.txt");
int a;
for(int i = 0;i<4;++i){
ifs>>a;
cout<<endl<<a;
if(i==0){
ifs.unget();
}
}
And the output is:
16 6 2 3
Why is the output like that? ( it should be 16 2 3 4 ) , it only occurs when I put ifs.unget() in the program , so my questions are , what is the purpose of cin.unget() while using I/O files and why is the number 6 ( as part of 16 ) getting outputted?
Thanks in advance for any help.
Something wrong with the documentation?
Makes the most recently extracted character available again.
At the end of your first loop iteration, 6 was the last extracted character (as the final digit of the extracted formatted int with value 16).
Unget does exactly that: it un-gets it.
The next operation has the 6 to work with. So, surprise, you get 6 next time.
I'm working on a c++ program that is supposed to eventually create a cross-reference table from a paragraph of words read in from a file using hashing. Right now I'm mainly working on reading in the input from the file and making sure the hash function is working properly.
Here a little more specifics on this portion of the problem:
The program is supposed to read in a paragraph from a file one word at a time until it reaches a "word" consisting of 10 "*"s. Below this line of *s are a few more lines of words that will be used to test the program later on.
With the code I have written, everything appears to be working properly (I've used the formula to calculate the index of a couple of the words and am getting the same answer as is being displayed), however, I'm not sure how to get the input to stop when I reach the line of 10 *s. So while this seems to be reading the file in correctly and performing the right calculations, it's performing these calculations for every word in the file.
Here's the code I've written:
#include <iostream>
#include <fstream>
using namespace std;
int hash(string word) {
int firstOff = word[0];
int lastOff = word[word.size() - 1];
int index = (firstOff * 256 + lastOff) % 23;
cout << index << endl;
return index;
}
int main() {
ifstream file;
file.open("prog7.dat");
if(!file.is_open()) {
cerr << "Error opening " << file << endl;
}
string word;
while(file >> word) {
hash(word);
}
}
Here's the output I'm getting:
12
6
17
21
1
21
12
14
11
12
7
14
16
10
2
22
19
21
22
7
7
12
21
21
3
9
3
12
14
14
0
3
21
7
6
7
12
7
17
6
2
16
21
7
14
And in case it helps, here's the file I'm using for the input:
the relative lack of acceptance
of these products in the
corporate marketplace is
due less to technical than
to political factors the
availability of this technology
threatens the perks privileges
and traditions of corporate
management
**********
the
political
lack
relative
less
forgive
tradition
factors
more
Can anyone help me out? I'd really appreciate it.
You can simply check for the word in the while condition:
while(file >> word && word != "**********") {
hash(word);
}
You could also break the loop when you reach the word (if you prefer how it looks).
while(file >> word) {
if (word == "**********") break;
hash(word);
}
Can also use an istream_iterator such as
#include <iostream>
#include <string>
#include <iterator>
#include <fstream>
using namespace std;
int main()
{
ifstream file("prog7.dat");
istream_iterator<string> it(file);
while(*it != "**********")
hash(*it++);
}
#include<iostream.h>
#include<fstream.h>
ifstream f("date.in");
using namespace std;
int i;
int P(int a[100],int k,int max)
{
max=a[1];
for(i=2;i<=k;i++)
if(a[i]>max)
max=a[i];
return max;
}
int main()
{
int x,a[100],n;
f>>n;
for(i=1;i<=n;i++)
f>>a[i];
for(i=2;i<=n;i++)
a[i]=P(a,i,x);
for(i=1;i<=n;i++)
cout<<a[i]<<" ";
}
My "date.in" file consists of the following :
12
4 6 3 7 8 1 6 2 7 9 10 8
As the title states, the program should modify the array from within the file such that each number has the maximum value found in the array up to, and including, the position of that respective number. I've gone through it a hundred times but cannot figure out what's wrong with my code.
When compiled, I get the following:
4 6 3 7 8 8 6 8 7 9 10 10
Any assistance would be appreciated.
int i;
Globals are usually a bad idea. Because this loop:
for(i=2;i<=n;i++)
a[i]=P(a,i,x);
and this loop:
for(i=2;i<=k;i++)
if(a[i]>max)
max=a[i];
are running "at the same time", and thus i in the first one is NOT counting from 2 to n properly, it's only actually getting the first index and then the even indexes. (Check your results, the even indexes are 100% correct: x 6 x 7 x 8 x 8 x 9 x 10). If you use counters local to each loop: for(int i=2; ... then this problem wouldn't be happening.
Also your entire design is slow. Not sure why you did it that way, because it can be done easily in a single pass: http://ideone.com/LmD0HX.
And use <iostream> not <iostream.h>. They're actually different files.
I need to get very basic input from an external file in C++. I tried searching the internet a few times but nothing really applied to what I need. This would be a .txt file that the input it coming from, and it would be filled with lines like this:
131
241
371
481
I have code already to manually get this input, and it looks like this:
using namespace std;
//Gets the initial values from the user.
int control=0;
while (rowb!=0){
cout << "Row: ";
cin >> rowb;
cout << "Column: ";
cin >> columnb;
cout << "Number: ";
cin >> numb;
row[control]=rowb-1;
column[control]=columnb-1;
num[control]=numb;
control++;
}
This is part of a program that solves sudoko boards. The inputed numbers are the initial values that a sudoko board holds, and the user is inputing the row, column, and number that comes from a board.
What I need is to be able to create a .txt file with these numbers stored in rows so that I do not have to enter so many numbers. I have very little idea how to go about doing this. Mainly I'll only be using the txt file for testing my program as I move along with adding more code to it. It takes 150+ entered numbers within my program just to get a single board, and it takes a lot of time. Any accidentally wrong entered value is also a huge problem as I have to start again. So how would I get C++ to read a text file and use those numbers as input?
Aside from the other suggestions, you can simply redirect a file to standard input, like so (where $ is the command prompt):
$ myprogram < mytextfile.txt
That will run myprogram just as normal but take input from mytextfile.txt as if you had typed it in. No need to adjust your own program at all.
(This works on both Unix/Linux systems and on Windows.)
You can open a file for input with std::ifstream from the header <fstream>, then read from it as you would from std::cin.
int main()
{
std::ifstream input("somefile.txt");
int a;
input >> a; // reads a number from somefile.txt
}
Obviously, you can use >> in a loop to read multiple numbers.
Create an std::ifstream object, and read from it just like you would from std::cin. At least if I understand what you're trying to do, the 131 as the first input is really intended to be three separate numbers (1, 3, and 1). If so, it's probably easiest to change your input file a bit to put a space between each:
1 3 1
2 4 1
3 7 1
4 8 1
Personally, I would start with a different format of the file: enter a value for each cell. That is, each row in the input file would represent a row in the sudoko board. Empty fields would use a space character. The immediate advantage is that the input actually pretty much looks like the sudoko board. Also, you would enter at most 90 characters: 9 characters for the board and a newline for each line:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
int main(int ac, char* av[])
{
std::ifstream in(ac == 1? "sudoko.init": av[1]);
char board[9][9];
for (int i(0); i != 9; ++i)
{
in.read(board[i], 9).ignore();
}
if (!in)
{
std::cout << "failed to read the initial board\n";
}
else
{
typedef std::ostream_iterator<char> iterator;
std::fill_n(iterator(std::cout << "board:\n\n+", "+"), 9, '=');
for (int i(0); i != 9; ++i)
{
std::copy(board[i] + 0, board[i] + 9, iterator(std::cout << "\n|", "|"));
std::fill_n(iterator(std::cout << "\n+", "+"), 9, (i + 1) % 3? '-': '=');
}
std::cout << "\n";
}
}
This would take input like this:
4 5 3 8
71 3
16 7
6 4 7
6 8
1 9 5
6 42
5 94
4 7 9 3
Note that each of these lines uses 9 characters. You might want to use something more visible like ..