i am new to c++ programming i am not able to store in a text file.It is a very simple program. i was storing the values using the same method earlier i was getting results.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ofstream fout("one.txt",ios::in);
int val1, rel1;
char val2[20], rel2[20];
cout<<" \n enter the integer value";
cin>>val1;
cout<<" \n enter the string value ";
cin>>val2;
fout.close();
ifstream fin("one.txt");
fin>>rel1;
fin>>rel2;
cout<<"the integer value .\n"<<rel1;
cout<<"the string value .\n"<<rel2;
fin.close();
if (fout==NULL) {
cout<<"the file is empty";
}
return 0;
}
input
100
name
Absurd output is
the integer value is 32760
the string value is 00Dv0
There's a number of assumptions here that seem to need clarification.
If you want to write to the file you need to use fout << rel1;
You (usually) can't compare an object against NULL like you do in if(fout == NULL). This works in C# and Java because in those languages all objects are actually references, in C++ you specify when you want an object and when you want a reference.
You specify that you want to use fout to read from the file and not write to it, "ios::in".
I was a bit bored waiting for some tests to finish so I wrote how I would've written that program:
#include<iostream>
#include <string>
#include<fstream>
int main() {
std::ofstream fout("one.txt",std::ios::out);
int val1, rel1;
std::string val2, rel2;
std::cout <<"enter the integer value: ";
std::cin >>val1;
std::cout <<"enter the string value: ";
std::cin >>val2;
fout <<val1 <<" " <<val2;
fout.close();
std::ifstream fin("one.txt", std::ios::in);
if(!fin.good()) {
std::cout <<"Failed to open file\n";
return 1;
}
fin >>rel1;
fin >>rel2;
std::cout <<"the integer value: " <<rel1 <<"\n";
std::cout <<"the string value: " <<rel2 <<"\n";
fin.close();
return 0;
}
Related
I've been tasked with writing a C++ program that opens a text file, determines the length of each word, then produces output stating how many times a particular word length occurs.
I've figured how to open and read the contents of the file.
How would I take each word and store them in an array?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void getFile(string);
void getFile(string filename)
{
string array[2];
short loop = 0;
string line;
ifstream myfile (filename);
if (myfile.is_open())
{
while (!myfile.eof() )
{
getline (myfile,line);
array[loop] = line;
cout << array[loop] << endl;
loop++;
}
myfile.close();
}
else{
cout << "can't open the file";
system("PAUSE");
}
}
int main(){
string fileName;
while (true){
cout << "\nEnter the name of a file: ";
getline(cin, fileName);
if (fileName == ""){
cout << "Invaled file name, enter another!!!"<<endl;
main();
}
else{
getFile(fileName);
}
}
return 0;
}
You do not store words in an array.
You only need to store the word lengths and how often each of them occurred.
If you have a guaranteed and low maximum word length you can even simplify by using an array where the length of the current word is used as an index. Init all entries with 0. Then count entries up when the corresponding word length occurs.
I have been having some problems with my code. I was asked to input elements from an .dat file into an array. For class we have to do this for various files without knowing how many elements will be in each file. The only thing we know is that here will never be more then 5000 elements per file.
One of my input file has the following elements:
5.675207 -0.571210
0.728926 0.666069
2.290909 0.751731 2.004545 0.907396
0.702893 0.646427 5.909504 -0.365045
2.082645 0.871841 5.597107 -0.633507
6.117769 -0.164663 6.091736 -0.190282
5.571074 -0.653433 4.503719 -0.978307
3.983058 -0.745620
3.670661 -0.504729
5.857438 -0.413001
When I run my code:
#define _CRT_NONSTDC_NO_DEPRECATE
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(int argc, char * argv[])
{
ifstream fin;
ofstream fout;
if (argc < 3)
{
cout << "Incorrect usage: prog.exe filenname number" << endl;
cout << "Exiting now, please try again." << endl;
return -1;
}
fin.open(argv[1]);
if (!fin)
{
cout << "Error opening file \"" << argv[1] << "\", exiting." << endl;
return -1;
}
fout.open(argv[2]);
int count = 0;
int word;
double points[5000];
while (fin >> word)
{
fin >> points[count];
++count;
}
fout << "Numer of points is: " << count/2 << endl;
for (int i = 0; i < count; i++)
{
fout << points[i] << " ";
}
fin.close();
fout.close();
return 0;
}
I outputted the elements just to make sure that they were properly inputted. I get the following and I don't know why.
0.675207 0.57121
0.728926 0.666069
0.290909 0.751731 0.004545 0.907396
0.702893 0.646427 0.909504 0.365045
0.082645 0.871841 0.597107 0.633507
0.117769 0.164663 0.091736 0.190282
0.571074 0.653433 0.503719 0.978307
0.983058 0.74562
0.670661 0.504729
0.857438 0.413001
The first digit is converted to a 0 for some reason and the negative ones become positive. Would anyone know why this is occurring?
int word;
is doing you no favours. First it's an integer so fin >> word only reads the integer portion of the inputs. 5.675207 is read as 5. the .675207 is left in the file stream for fin >> points[count]. Words isn't stored anywhere to the 5 is discarded but the .675207 lives on as 0.675207 in points[0].
Where the negative signs are going I didn't bother trying to figure out because
while (fin >> points[count])
{
++count;
}
fixes everything.
When you read in the numbers from the the file you are extracting them as "word" and then storing them as "points". "word" is an integer and "points" is a double, this will give you unexpected behavior. The compiler should give you warnings about this.
Here's my actual code, it's skipping the getline(cin,phrase) completely..
maybe there's something else wrong with it, but I can't really find anything wrong.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ofstream outFile;
string file_name;
string phrase;
int number;
cout << "What file would you like to write into? ";
cin >> file_name;
outFile.open(file_name);
if(!outFile)
{
cout << "Error, could not find file. Press enter to self destruct. " << endl;
return -1;
}
cout << "What would you like to write? ";
getline (cin, phrase);
cout << "How many times? ";
cin >> number;
while(number != 0)
{
outFile << phrase;
number = number - 1;
}
system("pause");
return 0;
}
cin would read as far as whitespace is not there in your input string. To get around that you can use
getline( cin, cookie ).
OR
char input[100];
cin.getline(input,100);
EDITED AS TO CLARIFY:-
Show me the output for this :-
#include <iostream>
#include <string>
using namespace std;
int main()
{
string cookie;
getline ( cin, cookie );
cout << cookie;
system("pause");
return 0;
}
The >> operators read formatted input in term of "space separated items", so
aaaaa bbbb 123
are actually three distinct elements. The first two can be string, the third can be a string or whatever numeric scalar type.
If you want to consider spaces as part of the read, the proper function shold be getline
I have this program that changes negative numbers to positive in my file.
It works, but negative numbers in the file don't change.
for example, if I have this numbers in my file : 12 2 -3 -1
when I run the program, the sum of numbers will be 18, but when I open my file again, I see
12 2 -3 -1 . What should I do to see 12 2 3 1 ?
here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string name;
cin >> name;
int number;
int num=0;
ifstream myFile(name, ios::in);
ofstream mine(name, ios::app);
while(myFile >> number)
{
num += (number<0 ? -number : number);
mine << num;
}
cout << "num = " << num << endl;
system("pause");
return 0;
}
Opening the file for reading and writing for the same time is generally not a bad idea. You probably got an I/O error during opening mine, but since you didn't check it, the program ignored your writes silently. Try reading the file contents first (to a vector for example), then close the file for reading and open again for writing (not appending, because that would leave the old contents in the file).
When writing the values back to the file, also write whitespace after the number, otherwise you'll just get a string of digits in the file but you won't know where one begins and another ends.
Your program now doesn't "change negative numbers to positive" but it prints the cumulative sum of absolute values to the file.
Try writing to the standard output first so you won't ruin your file while you are testing. If it works, then change cout to your output stream.
Here is the code.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
string name;
cin >> name;
int number;
int num=0;
ifstream myFile(name, ios::in);
vector<int> vec;
while(myFile >> number)
{
vec.push_back(abs(number));
}
ofstream mine(name, ios::out);
for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
num += *it;
mine << *it << " ";
}
cout << "num = " << num << endl;
return 0;
}
Opening a read and write file streams for the same file and process at the same time is inviting file corruption. Use ostringstream to store the values read from the file. The values
from the file are read, and the values stored in the ostringstream
buffer. The ifstream object is closed before re-opening the file with
an ofstream object so that the buffer contents can be saved.
Note the ios::app flag has been removed. Otherwise the new values
will append to the existing values.
abs() function is used to write back the absolute values - this
forces all values positive.
#include<sstream>
int main()
{
string name;
cin >> name;
int number;
int num=0;
ifstream myfile(name.c_str(), ios::in);
ostringstream oss;
while (myfile >> number)
{
num += (number<0 ? -number : number);
oss << abs(number) << " ";
}
myfile.close();
ofstream mine(name.c_str());
cout << "num = " << num << endl;
mine << oss.str();
return 0;
}
string name;
cin >> name;
int number=0;
int sum=0;
string outname=name+".pos.txt";
ifstream myFile(name,ifstream::in);
ofstream mine(outname, ofstream::out );
while(myFile >> number)
{
number= (number<0 ? -number : number);
sum+=number;
mine << number<<' ';
}
myFile.close();
mine.close();
cout << "sum = " << sum << endl;
system("pause");
First, I'm very new to coding in C++.
So, I have a .txt file, with names and numbers--here's an example.
chris 5
tara 7
Sam 13
Joey 15
I would like to use this code to retrieve the names and numbers, but how does one print specific array entries instead of just the variables name and number (I want it to show the name and the number on the screen)?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string name;
int number;
struct sEntry
{
std::string name;
int number;
};
sEntry entries[256];
std::ifstream fin("input.txt"); // opens the text file
int nb_entries; // Keeps track of the number of entries read.
for (nb_entries = 0; fin.good() && nb_entries < 256; nb_entries++) // Keep going until we hit the end of the file:
{
fin >> entries[nb_entries].name;
fin >> entries[nb_entries].number;
cout << "Here, "<< name <<" is name.\n";
cout << "Here, "<< number <<" is number.\n";
}
}
You're writing out name and number, but those aren't the variables you've read. You've read array entries.
Getting it working as simply as possible just comes down to changing your cout lines to be:
cout << "Here, " << entries[nb_entries].name << " is name.\n";
cout << "Here, " << entries[nb_entries].number << " is number.\n";
No need for a std::vector, ther's nothing wrong with how you've done it.
Instead of using a plain C array of sEntry you should use a C++ vector instead (which can change size dynamically). Then you create a new sEntry instance inside your loop (which can just use fin.eof() as termination condition then) and use the operator>>() to assign the values. Afterwards you use push_back() to add the sEntry instances to your vector.
You need to use the sEntry.name, sEntry.number fields for output on the screen, name and number as shown in your code won't ever receive values.
#include <vector>
#include <string>
#include <iostream>
struct sEntry
{
std::string name;
int number;
};
int main() {
string name;
int number;
std::vector<sEntry> entries;
std::ifstream fin("input.txt"); // opens the text file
// int nb_entries; // Keeps track of the number of entries read. -> not necessary, use entries.size()
while(!fin.eof()) // Keep going until we hit the end of the file:
{
sEntry entry;
fin >> entry.name;
fin >> entry.number;
cout << "Here, "<< entry.name <<" is name.\n";
cout << "Here, "<< entry.number <<" is number.\n";
entries.push_back(entry);
}
}