C++ - Read from file to double [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm relatively new to programming and taking a course in C++ currently. I haven't had any major problems so far. I am making a program where an X amount judges can score 0.0 - 10.0 (double) and then the highest and lowest one is removed then an average is calculated and printed out.
This part is done, now I want to read from a file in the shape of:
example.txt -
10.0
9.5
6.4
3.4
7.5
But I am stumbling onto problems with the dot (.) and how to get around it to get the number into a double. Any suggestions and (good) explanations so I can understand it?
TL;DR: Reading from file (E.G. '9.7') to a double variable to put into an array.

Since your textfile is whitespace delimited, you can use that to your advantage by utilizing std::istream objects who skip whitespace by default (in this case, std::fstream):
#include <fstream>
#include <vector>
#include <cstdlib>
#include <iostream>
int main() {
std::ifstream ifile("example.txt", std::ios::in);
std::vector<double> scores;
//check to see that the file was opened correctly:
if (!ifile.is_open()) {
std::cerr << "There was a problem opening the input file!\n";
exit(1);//exit or do additional error checking
}
double num = 0.0;
//keep storing values from the text file so long as data exists:
while (ifile >> num) {
scores.push_back(num);
}
//verify that the scores were stored correctly:
for (int i = 0; i < scores.size(); ++i) {
std::cout << scores[i] << std::endl;
}
return 0;
}
Note:
It is highly recommended to use vectors in lieu of dynamic arrays where possible for a myriad number of reasons as discussed here:
When to use vectors and when to use arrays in C++?

Try this:
#include <iostream>
#include <fstream>
int main()
{
std::ifstream fin("num.txt");
double d;
fin >> d;
std::cout << d << std::endl;
}
Does that do what you want?

Related

Using cout << endl; between functions fixes code [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have simplified the code to get rid of unrelated objects. This is my code:
#include <iostream>
#include <fstream>
using namespace std;
fstream asdf;
int input;
void import_image(){
asdf.seekg(0);
char character;
for(int k = 0; k < 40; k++){
asdf.get(character);
input = (unsigned int)(unsigned char)character;
}
}
void print_hello_world(){
for(int rows; rows <= 27; rows++){
cout << "hello world" << endl;
}
cout << "goodbye.";
}
int main(){
asdf.open("abc.txt", ios::binary | ios::in);
cout << asdf.is_open() << endl;
import_image();
//cout << endl;
print_hello_world();
return 0;
}
Running this code results only in
1
goodbye.
--------------------------------
Process exited after 0.1511 seconds with return value 0
however removing double slash (simply adding cout << endl;) fixes everything. I have no idea why it happens and would like to now why is it so. I know that variable "rows" has no value, but why does printing a new line fix everything?
The new "endl"
is a great sign
that what you see,
is called "UB".
Your program has Undefined Behavior (UB) because your int rows that you use for the loop iterations is uninitialized.
By UB definition anything may happen. Activate all (sane) compiler warnings to find errors like this earlier in your development process.
Undefined behavior yield working programs by completely random changes (for example the addition of std::endl) but in the end it's undefined behavior.

How to count a certain character within a file C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
int main()
inFile.get(file);
while(inFile) {
inFile.get(file);
cout << file;
if(inFile.fail()) {
break;
}
if(inFile) {
++charNum;
}
if(inFile && c =='<') {
++comNum;
}
The values keep outputting 1, and its not actually counting the amount of < in the file. If I put inFile >> c, it makes my file a bunch of gibberish. What is the best way to count a certain amount of characters within a file, that is being opened by the user? Thank you.
You can rely on algorithms provided by the Standard Library.
#include <algorithm>
#include <fstream>
#include <iostream>
int main(int argc, char* argv[]) {
std::ifstream fp(argv[1]);
const auto count = std::count(std::istreambuf_iterator<char>{fp},
std::istreambuf_iterator<char>{}, '<');
std::cout << "count: " << count << "\n";
}

My output file is not displaying the solution [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
My output file is supposed to show to answer to the function it calls on. The program runs fine, however it is not displaying the text in the "prime" function. the output file, when checked, only displays 1's. I believe this is due to the fact that its declared as a bool function, and set to return true. However, how would I get this code to return the solution in Prime to the output file?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
bool prime(int);
int main()
{
int reader;
ifstream Infile;
Infile.open("numlist.txt");
ofstream outputFile;
outputFile.open("theoutput.txt");
while (Infile >> reader)
{
outputFile << prime(reader) <<endl;
}
Infile.close();
outputFile.close();
}
bool prime(int p)
{
if (p % 2 == 0)
cout << "\n" << p << "\n Is not a prime number";
else if (p % 2 != 0)
cout << "\n" << p << "\n is a prime number";
return true;
}
No errors, however the output file is only showing 1's.
This is happening because in your prime() function, all the output is going to cout and not into outputFile. The prime() function returns a bool which is what is sent to outputFile.
If you'd like to have output of the function go to outputFile, you can either pass outputFile as a parameter and use that instead of cout or make it global.
A few more comments on your code: you don't need the full else if (p % 2 != 0) in the else statement. You can just use else, because p % 2 is either 0 or it's not, there's no other option.
Also, strongly recommend using braces around if statements, even if they are just a single line.

Can't erase digits from c++ string by using the 'erase' function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Using c++ 14.
I'm prompting the user for a string containing both letters and integers, and trying to "strip" the integers from the string itself via the string.erase() function.
The problem i'm facing is when there are 2 or more sequential numbers, than the function seems to erase the first but delete the latter.
Example:
input: H23ey Th2e3re St01ack O34verflow
output: H3ey There St1ack O4verflow
I can do it another way by using a new string, looping through the existing one and adding only what isalpha or isspace, but it seems messier.
code:
string digalpha {};
cout << "Enter string containing both numbers and letters: ";
getline(cin, digalpha);
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1);
cout << digalpha << endl;
cout << endl;
return 0;
In the first sentence you were writing that you are using C++14.
In "more modern" C++ the usage of algorithm is recommended. So normally you would not use C-Style For loops.
The standard approach that you can find everywhere, is a combination of erase with std::remove_it. You will find this construct in many many examples.
Please consider to use such a solution instead of a for loop.
You can even include the output in an algorithm using std::copy_if.
Please see:
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
std::string test1{ "H23ey Th2e3re St01ack O34verflow" };
std::string test2{ test1 };
// C++ standard solution for erasing stuff from a container
test1.erase(std::remove_if(test1.begin(), test1.end(), ::isdigit), test1.end());
std::cout << test1 << "\n\n";
// All in one alternative
std::copy_if(test2.begin(), test2.end(), std::ostream_iterator<char>(std::cout), [](const char c) { return 0 == std::isdigit(c); });
return 0;
}
If there's two digits next to each other, it skips the second digit. This happens because the index, i, keeps going up, even though everything got shifted over:
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1); //Here, i goes up anyway, skipping character after digit
To fix this, we just have to decriment i after erasing a digit:
for (size_t i {}; i < digalpha.size(); i++) {
if (isdigit(digalpha.at(i))) {
digalpha.erase(i,1);
i--;
}
}

C++: Counting the frequency of ASCII characters in file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am a beginner to C++ and have been pondering this problem for quite a while, but I'm finding myself unable to come up with a solution and was hoping I could find some direction here.
I have an input file that will contain any number of ASCII characters (ex: hello, world; lorem ipsum; etc.). My program will read this file and count the frequency of each ASCII character, outputting the end counts when EOF is reached. I believe I need to use array[128] for the counters, but besides that, I'm totally stuck.
Here's what I have so far (it's not much and only reads the characters from the file):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
ifstream inputFile;
string infile;
char ch;
//char ascii;
//int asciiArray[128] = {0};
// Gets input filename from user, checks to make sure it can be opened, and then
// gets output filename from user.
cout << "Please enter your input filename: ";
cin >> infile;
inputFile.open(infile.c_str());
if (inputFile.fail())
{
cout << "Input file could not be opened. Try again." << endl;
exit(0);
}
// Gets the first character of the input file.
inputFile.get(ch);
while(!inputFile.eof())
{
inputFile.get(ch);
}
// Closes the input file
inputFile.close();
return 0;
}
Any direction or help would be greatly appreciated. I have a feeling I will need to use pointers to solve this...but I've just barely started covering pointers, so I'm very confused. Thanks!
Edit: I removed some variables and it's working now, looks like I forgot them there while I was brainstorming. Sorry for leaving it unworking and not mentioning why; I won't do that again!
You should write your loop as:
while(inputFile >> ascii)
{
asciiArray[ascii]++;
}
Note that I don't directly check for eof in the loop condition since that's almost always wrong.
Also you should be sure that your file is indeed written with ascii characters only. Since any character outside the ascii range would result in an out of bounds access to the asciiArray.
In regular Ascii you have 128 chars... of which each char can be evaluated as an int.
That is the key in solving this puzzle.
Just remember you have 128 possible chars, an array with 128 values, and each char represents a number from 0-127.
Also recall that you can do stuff like this:
int i = 97;
char a = i;
char b = a + 1;
cout << (int)i << (int)a << (int)b << endl;
// 979798
cout << (char )i << (char )a << (char )b << endl;
// aab
cout << i << a << b << endl;
// 97ab
As far as pointers go, the only way I would see them as being used is if you used pointer notation instead of array notation while manipulating your variable asciiArray