I'm stuck on how to read from a text file - c++

/* In the text file I have a char followed by a blankspace then a string. I'm trying to read the char and string into seperated arrays. Any help is appreciated */
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
char arrivOrDepart;
string licensePlt;
ifstream inFile;
inFile.open("Text.txt");
if (!inFile)
{
cout << "Can't open file" << endl;
return 1;
}
for (int i = 0; i < 4; i++)
{
getline(cin, arrivOrDepart[i]);
getline(cin, licensePlt[i]);
}
inFile.close();
cin.get();
return 0;
}
//text file
A QWE123
A ASD123
A ZXC123
A WER123
A SDF123

#include <fstream>
#include <iterator>
#include <vector>
this reads from file into vector
std::ifstream input("d:\\testinput.txt");
std::vector<std::string> bytes(
(std::istreambuf_iterator<std::string>(input)),
(std::istreambuf_iterator<std::string>()));
input.close();
then, just put the data into whatever container you want. you should almost always prefer vector over array btw

There are a few problems with the code:
getline is the wrong tool of choice for this. if you want to split a stream based on spaces, use >>.
arrivOrDepart and licensePlt are not defined as arrays but are used as arrays.
reading from cin, not from file.
My suggested fixes (excluding using vectors instead of arrays):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std; // avoid using this
int main()
{
const int MAXARRAY = 4; // avoid using magic numbers
char arrivOrDepart[MAXARRAY]; // made an array, but prefer std::vector
string licensePlt[MAXARRAY]; //made an array
ifstream inFile;
inFile.open("Text.txt");
if (!inFile)
{
cout << "Can't open file" << endl;
return 1;
}
string temp;
int i = 0;
while (i < MAXARRAY && // not overrunning the arrays
inFile >> temp >> licensePlt[i] && // read data from file stream
temp.length() == 1) // read only one character for arrivOrDepart
{
arrivOrDepart = temp[0];
i++;
}
inFile.close();
cin.get();
return 0;
}
Recommended reading:
Why is "using namespace std" considered bad practice?
What is a magic number, and why is it bad?
std::vector documentation (Alternate easier to read but often less accurate documentation)
std::getline documentation. Note the third parameter used to set the parsing delimiter.

Related

c++ how to read and write from a specific line in a textfile?

hi I am trying to read a specific line from a text file update that and put it back to the same line without affecting the other lines in c++
here I am trying to execute the code and values get added when I re-execute it
#include <iostream>
#include <stream>
#include <stdio.h>
#include <string>
#include <stream>
using namespace std;
void stringGen(char num){
ifstream ifile;
ifile.open("example1.txt");
if(ifile) {
int LINE = 5;
string line;
ifstream myfile1 ("example1.txt");
for (int i = 1; i <= LINE; i++)
getline(myfile1, line);
cout << line<<endl;
stringstream geek(line);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
ofstream MyFile("example1.txt");//
MyFile.close();
}
else{
num=61001;
ofstream MyFile("example1.txt");//
MyFile << num;
MyFile.close();
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("example1.txt");//
MyFile << num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}
At first, you need to understand, how files, with lines are stored. Simplified, it is a sequence of bytes, one byte after the other. There maybe some special characters in this byte sequence, which people can interprete as the end of a line, e.g. '\n'. But also other characters or even more than one character is possible:
If you look at the following text.
Hello1
World1
Hello2
World2
it maybe stored in a file like this:
Hello1\nWorld1\nHello2\nWorld2\n
And just because we interprete a '\n' as the end of the line, we can "see" lines in there.
So, if you want to modify a line, then you would need to find the start position of the thing that we interprete as a line in the file, and then modify some bytes.
That can of course only be done, if the length of the "line" will not change. Then you could use "seek" functions and overwrite the needed bytes.
In reality, nobody would do that. Normally, you would read "lines" of the file into some kind of memory buffer, then do the modification there and then write back all lines.
For example, you would define a std::vector and then read all lines, by using std::getline and push_back the lines in the std::vector.
The modifications will be done in the std::vector, and the all data will be written back to the file, overwriting all "old" data.
There are more answers to this question. If you have any more specific question, I will answer again
Some simple example code
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
// Here we will store all lines of the text file
std::vector<std::string> lines{};
// Open the text file for reading and check, if it could be opened
if (std::ifstream textfileStream{ "test.txt" }; textfileStream) {
// Read all lines into our vector
std::string oneLine{};
while (std::getline(textfileStream, oneLine)) {
// Add the just read line to our vector
lines.push_back(oneLine);
}
// For test purposes, modify the first line
if (not lines.empty()) lines[0] = "MODIFIED";
}
else std::cerr << "\nError: Could not open input text file\n";
// Write back data
// Open the text file for writing and check, if it could be opened
if (std::ofstream textfileStream{ "r:\\test.txt" }; textfileStream) {
// Iterate over all lines and wriite to file
for (const std::string& oneLine : lines)
textfileStream << oneLine << '\n';
}
else std::cerr << "\nError: Could not open output text file\n";
return 0;
}
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
void stringGen(char num){
int count=0;
int a;
string line,check,linex;
string msg="Message_Handler:";
fstream ifile;
ifile.open("sample.txt",ios::in|ios::out);
if(ifile){
while(getline (ifile,line)) {
if (line.find("Message_Handler:") == 0){
check=line.substr(16,5);
count++;
a=ifile.tellp();
}
}
ifile.close();
if(count==0){
int num=61001;
cout<<num<<endl;
num=num+1;
ofstream examplefile ("sample.txt",ios::app);
examplefile<<"Message_Handler:"<<num;
examplefile.close();
}
if(count==1){
cout<<check<<endl;
stringstream geek(check);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
else{
int num=61001;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("sample.txt",ios::app);
MyFile <<"Message_Handler:"<< num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}

Count one certain string in a file in C++

This is my code.
I am supposed to count the number of 'duck' in a txt file and print string like "There were 2 ducks in animals01.txt"
Now I get no error and nothing return.
Please tell me what's wrong?
#include <iostream> // for printf()
#include <cstdlib> // for exit(), perror()
#include <fstream> // for ifstream
using namespace std;
int main(int argc, char *argv[])
{
if (argc!=2) {
// if argc is not 2, print an error message and exit
cerr << "Usage: "<< argv[0] << " inputFile" << endl;
exit(1); // defined in cstdlib
}
return 0;
int num = 0;
ifstream ifs;
ifs.open(argv[1]);
string line;
do{
getline(ifs, line);
cout<<line<<endl;
if(line == "duck"){num++;}
}while(!ifs.eof());
cout<<"There were"<<num<<"ducks in"<<argv[1]<< endl;
}
You have the line return 0; before you actually did anything, and when you return main() the program is terminated.
By the way, don't use while(!ifs.eof()) because the eof flag only gets set at the first attempt to read past the end of the file, not when you read exactly to the end of the file due to a line break at the end. Do something like this. Also, fix your indenting as it is very misleading.
Read the file word by word.
Example:
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string str, strToSearch = "ducks";
int wordCount = 0;
ifstream fin("thisfile.txt");
while (fin >> str) // Will read up to eof() and stop at every whitespace it hits. (like spaces!)
{
if(str==strToSearch)
wordCount++;
}
fin.close();
cout<<"There were"<<wordCount<<"ducks in thisfile.txt"<<endl;
return 0;
}

Trying to open file and copy it word by word with vector

I'm trying to open a file and read it word by word. I can't figure out where my issue is as it seems to break down after opening the file.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
There are two problems here:
You opened inputFile but then attempt to read from std::cin
"while (!inputFile.eof())" is always the wrong thing to do.
Well, there's also a third problem here:
Using a debugger would've immediately identified both problems. As an example, I loaded the compiled code in a debugger and stepped through it. The issues were readily apparent.
#Sam has all the things you did wrong.
But an alternative to using a loop is just to use iterators to build the array.
std::ifstream file(path);
std::vector<std::string> words(std::istream_iterator<std::string>(file),
std::istream_iterator<std::string>());
To print it out you can use copy.
std::copy(std::begin(words), std::end(words),
std::ostream_iterator(std::cout, "\n"));
Currently this will break words using white space as the separator between words. This means punctuation etc will be included with words. Look here on how to get the streams to treat punctuation as space: How to tokenzie (words) classifying punctuation as space
Thanks to everyone for the help. Here is the final code (for anyone who ends up Googling this in the future)
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (inputFile >> test)
{
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}

code to read-in floating variables from a textfile containing more than one line

In c++ how would I read a text file containing 3 float variables not as string types, but as float variable types for re-use by a program.
I was trying to use fscanf function and having results of it only reading in the first line of the file. How do I tell it to use delimiters such as \n end of line and have it continue to process the rest of the file?
Thanks.
#include <cstdlib>
#include <math.h> //Include math functions
#include <iostream> //Stream to allow input/output
#include <fstream> //Stream class to read/write files
using namespace std;
string line = "0.0";
char str [80];
float f;
FILE * pFile;
int main () {
pFile = fopen ("C:\\Users\\Brian\\Documents\\NetBeansProjects\\CppApplication_2\\init_temps.txt","r"‌​);
fscanf (pFile, "%f", &f);
cout << f;
return 0;
}
Based on your code, it seems you are only reading the first number. You should iterate 3 times:
int i;
for(i = 0; i < 3; i++)
{
fscanf(pFile, "%f", &f);
cout << f << endl;
}
or better yet check for fscanf()'s return value to better decide if you've read it all.
On another note, you should learn to use local variables instead of global variables, unless there's really a need to.
Hope this helped.
floats.text
5.5
2.2
1.1
read.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
float sum = 0;
ifstream myfile ("floats.text");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
sum += ::atof(line.c_str());
}
myfile.close();
}
cout << sum << endl;
return 0;
}
result
./a.out
>> 8.8

C++ Putting text from a text file into an array as individual characters

I want to put some text from a text file into an array, but have the text in the array as individual characters.
How would I do that?
Currently I have
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string line;
ifstream myfile ("maze.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
// --------------------------------------
string s(line);
istringstream iss(s);
do
{
string sub;
iss >> sub;
cout << "Substring: " << sub << endl;
} while (iss);
// ---------------------------------------------
}
myfile.close();
}
else cout << "Unable to open file";
system ("pause");
return 0;
}
I'm guessing getline gets one line at a time. Now how would I split that line into individual characters, and then put those characters in an array?
I am taking a C++ course for the first time so I'm new, be nice :p
std::ifstream file("hello.txt");
if (file) {
std::vector<char> vec(std::istreambuf_iterator<char>(file),
(std::istreambuf_iterator<char>()));
} else {
// ...
}
Very elegant compared to the manual approach using a loop and push_back.
#include <vector>
#include <fstream>
int main() {
std::vector< char > myvector;
std::ifstream myfile("maze.txt");
char c;
while(myfile.get(c)) {
myvector.push_back(c);
}
}