I have to read lines from an extern text file and need the 1. character of some lines.
Is there a function, which can tell me, in which line the pointer is and an other function, which can set the pointer to the begin of line x?
I have to jump to lines before and after the current position.
There is no such function i think. You will have to implement this functionality yourself using getline() probably, or scan the file for endline characters (\n) one character at a time and store just the one character after this one.
You may find a vector (vector<size_t> probably) helpful to store the offsets of line starts, this way you might be able to jump in the file in a line-based way. But haven't tried this, so it may not work.
You may ake a look at ifstream to read your file in a stream, then use getline() to get each line in a std::string.
Doing so, you can easily iterate trough the lines and grab the characters you need.
Here is an example (taken from here):
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl; // Here instead of displaying the string
// you probably want to get the first character, aka. line[0]
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Related
I have a file which looks like this:
2,1,4,6,7
1,2,3,6,5
I have to count the the digits in a single line while ignoring the comma. For example, the first line has 5 digits, and so does the second line. The number of digits can vary in each line. I used getline with a comma delimeter. However, if I do that, I don't know when the line ends. The code I have written will give me the count for whole file. All I want is a way to count the digits in a single line. How do I do that?
numberofdigits = 0;
while(!friendsFile.eof())
{
getline(friendsFile,counts,',');
intcounts = stoi(counts);
cout << intcounts;
numberofdigits++;
}
Combine your solution with reading line by line, and with a little help of std::stringstream:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
int main() {
std::ifstream input{"input.txt"};
if(!input) {
std::cerr << "Failed to open the file\n";
return 1;
}
std::size_t line_number = 0;
std::istringstream stream{};
for(std::string line{}; std::getline(input, line); stream.clear()) {
stream.str(line);
std::size_t count = 0;
std::string number{};
while(std::getline(stream, number, ',')) {
++count;
}
std::cout << "Line " << line_number++ << " contains " << count << " digits\n";
}
}
After you make sure that the file was opened successfully, you can start processing the file.
First, pay attention to the for() loop. We use a line string to save a line read from the file. The condition of the loop is also the part where we read the line. std::getline not only reads a line, but also returns the stream from where it was reading. That stream can be implicitely convered to bool to check whether the stream is in a valid state. By doing that, we are reading the file line by line and making sure that if something goes wrong (i.e., we reach end of the file), we won't enter the loop and use, potentially corrupted, data. That's a big difference between using this method and !file.eof(), which is almost always wrong.
Then, after reading a line, we initialize an std::istringstream object with it. Stringstreams are useful helpers which enable us to operate on text as though it was a stream. We again use std::getline, but this time to extract all the tokens separated by ','.
The stream.clear() part in necessary after we process a single line, because it clears all bad states of the stream (i.e., the state of reaching end of file - in our case, after reading the whole line).
We count the number of successfull extractions and display it on the screen.
I've been trying to read some information in from a .txt file in C++ but it's not all working like I expect. Here is some example code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char words[255];
int value = 0;
ifstream input_stream("test.txt");
input_stream >> value;
input_stream.getline(words, 256);
cout << value << endl;
cout << words << endl;
}
And test.txt contains:
1234
WordOne WordTwo
What I expect is for the code to print the two lines contained in the text file, but instead I just get:
1234
I've been reading about getline and istream but can't seem to find any solutions so any help would be appreciated.
Thanks
The newline character remains in the input stream after the read of the integer:
// Always check result to ensure variables correctly assigned a value.
if (input_stream >> value)
{
}
Then, the call to getline() reads the newline character and stops, producing an empty string. To correct, consume the newline character before calling getline() (options include using getline() or ignore()).
Note there is a version std::getline() that accepts a std::string as its argument to avoid using a fixed sized array of char, which is used incorrectly in the posted code.
ifstream's getline method gathers input until one of two options is hit. Either a terminating character or the size passed in is reached. In your case, the newline terminator is encountered before the size is reached.
Use another getline to retrieve the second line of text.
Reference
The problem you are seeing is that the first newline after 1234 is not consumed by input_stream>>(int); so the next getline only reads to the end of that file.
This is a very constructed scenario, commonly found in schoolwork. The more common scenario when reading a textfile is to consider the entire file as linebased text.
In this case the more convenient
string line;
while( std::getline( input_stream, line ) ){
}
is appropriate, and way less error prone.
The textfile would commonly have a predefined format. Perhaps name = value lines, and are parsed as such after the line is read from the file.
Here is a somewhat corrected version of your original code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char words[256]; // was 255
int value = 0;
ifstream input_stream("test.txt");
input_stream >> value;
input_stream.ignore(); // skip '\n'
input_stream.getline(words, 256);
cout << value << endl;
cout << words << endl;
}
Also, I would advise you to use a string instead of a char[] and use the other getline function.
I have a phone.txt like:
09236235965
09236238566
09238434444
09202645965
09236284567
09236235965
..and so on..
How can I process this data line by line in C++ and add it to a variable.
string phonenum;
I know I have to open the file, but after doing so, what is done to access the next line of the file?
ofstream myfile;
myfile.open ("phone.txt");
and also about the variable, the process will be looped, it will make the phonenum variable the current line its processing from the phone.txt.
Like if the first line is read phonenum is the first line, process everything and loop; now the phonenum is the 2nd line, process everything and loop until the end of the last line of the file.
Please help. I'm really new to C++. Thanks.
Read the comments inline please. They will explain what is going on to assist you in learning how this works (hopefully):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main(int argc, char *argv[])
{
// open the file if present, in read mode.
std::ifstream fs("phone.txt");
if (fs.is_open())
{
// variable used to extract strings one by one.
std::string phonenum;
// extract a string from the input, skipping whitespace
// including newlines, tabs, form-feeds, etc. when this
// no longer works (eof or bad file, take your pick) the
// expression will return false
while (fs >> phonenum)
{
// use your phonenum string here.
std::cout << phonenum << '\n';
}
// close the file.
fs.close();
}
return EXIT_SUCCESS;
}
Simple. First, note that you want an ifstream, not an ofstream. When you're reading from a file, you're using it as input - hence the i in ifstream. You then want to loop, using std::getline to fetch a line from the file and process it:
std::ifstream file("phone.txt");
std::string phonenum;
while (std::getline(file, phonenum)) {
// Process phonenum here
std::cout << phonenum << std::endl; // Print the phone number out, for example
}
The reason why std::getline is the while loop condition is because it checks the status of the stream. If std::getline fails in anyway (at the end of your file, for example), the loop will end.
You can do that :
#include <fstream>
using namespace std;
ifstream input("phone.txt");
for( string line; getline( input, line ); )
{
//code
}
I have a problem working in C++ with txt files.. First of all, I want to make a program which
have .cpp and .h files.. which have classes and functions.
So here is my problem:
for example, i have txt file which contains 5 lines of text (players names). So I want to make every line of that txt to be a variable of string.. But as long as I want to use that new variables they suddently disappears.
Here is program code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
int i;
string player[5];
ifstream myfile ("1-Efes Pilsen.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
for (i=0;i<5;i++)
{
getline (myfile,line);
player[i] = line;
}
// after this point I still can use new variables
}
}
else cout << "Unable to open file";
cout << player[1]; // <--- NOT WORKING. WHY?
myfile.close();
}
While it is not clear to me how it's not working, I can guess that there are more contents in the file than just 5 strings (perhaps another newline) which causes the while condition to evaluate to true causing the for loop to read 5 lines (which will fail and not actually read anything) and replace the good values in the string array with crappy ones (empty string).
Instead of having an outer while loop, you probably want to add the condition to the for loop itself; something along the lines of:
for (i=0;i<5 && myfile.good();i++)
{
getline (myfile,line);
player[i] = line;
}
How can I make my std::fstream object start reading a text file from the second line?
Use getline() to read the first line, then begin reading the rest of the stream.
ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
...
(Changed to std::getline (thanks dalle.myopenid.com))
You could use the ignore feature of the stream:
ifstream stream("filename.txt");
// Get and drop a line
stream.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
// Get and store a line for processing.
// std::getline() has a third parameter the defaults to '\n' as the line
// delimiter.
std::string line;
std::getline(stream,line);
std::string word;
stream >> word; // Reads one space separated word from the stream.
A common mistake for reading a file:
while( someStream.good() ) // !someStream.eof()
{
getline( someStream, line );
cout << line << endl;
}
This fails because: When reading the last line it does not read the EOF marker. So the stream is still good, but there is no more data left in the stream to read. So the loop is re-entered. std::getline() then attempts to read another line from someStream and fails, but still write a line to std::cout.
Simple solution:
while( someStream ) // Same as someStream.good()
{
getline( someStream, line );
if (someStream) // streams when used in a boolean context are converted to a type that is usable in that context. If the stream is in a good state the object returned can be used as true
{
// Only write to cout if the getline did not fail.
cout << line << endl;
}
}
Correct Solution:
while(getline( someStream, line ))
{
// Loop only entered if reading a line from somestream is OK.
// Note: getline() returns a stream reference. This is automatically cast
// to boolean for the test. streams have a cast to bool operator that checks
// good()
cout << line << endl;
}
The more efficient way is ignoring strings with std::istream::ignore
for (int currLineNumber = 0; currLineNumber < startLineNumber; ++currLineNumber){
if (addressesFile.ignore(numeric_limits<streamsize>::max(), addressesFile.widen('\n'))){
//just skipping the line
} else
return HandleReadingLineError(addressesFile, currLineNumber);
}
HandleReadingLineError is not standart but hand-made, of course.
The first parameter is maximum number of characters to extract. If this is exactly numeric_limits::max(), there is no limit:
Link at cplusplus.com: std::istream::ignore
If you are going to skip a lot of lines you definitely should use it instead of getline: when i needed to skip 100000 lines in my file it took about a second in opposite to 22 seconds with getline.
Call getline() once to throw away the first line
There are other methods, but the problem is this, you don't know how long the first line will be do you? So you can't skip it till you know where that first '\n' is. If however you did know how long the first line was going to be, you could simply seek past it, then begin reading, this would be faster.
So to do it the first way would look something like:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
// Open your file
ifstream someStream( "textFile.txt" );
// Set up a place to store our data read from the file
string line;
// Read and throw away the first line simply by doing
// nothing with it and reading again
getline( someStream, line );
// Now begin your useful code
while( !someStream.eof() ) {
// This will just over write the first line read
getline( someStream, line );
cout << line << endl;
}
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string textString;
string anotherString;
ifstream textFile;
textFile.open("TextFile.txt");
if (textFile.is_open()) {
while (getline(textFile, textString)){
anotherString = anotherString + textString;
}
}
std::cout << anotherString;
textFile.close();
return 0;
}
this code can read file from your specified line from file but you have to make file in file explorer before hand my file name is "temp" code is given below
https://i.stack.imgur.com/OTrsj.png
hope this can help
You can use ignore function as follow:
fstream dataFile("file.txt");
dataFile.ignore(1, '\n'); // ignore one line
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char buffer[256];
ifstream myfile ("test.txt");
// first line
myfile.getline (buffer,100);
// the rest
while (! myfile.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}