Reading an ASCII file with fstream - c++

Have an ASCII text file with some integer numbers in it, each separated by a space, and sometimes the numbers go on to a new line. For example:
// my_file.txt
23 45 973 49
44 1032 33 99
43 8 4 90824
I want to read 100 of these numbers into an array of "ints". Thus far, I have the following code:
int x[100];
fstream file_in("my_file.txt", ios::in);
for (int i = 0; i < 100; i++)
{
file_in >> x[i];
}
However, I now want to do a couple of other things that I am not sure about.
What if I want to just read the entire file in, without having to go through the loop? If this was binary data, I know that I can just write file_in.read((char*)&x[0], 100 * sizeof(int)). But how can I do this with an ASCII file?
What if I want to skip the first 3 numbers in the file, and start reading from the fourth? Again, if this was binary data, I could just use file_in.seekg(3 * sizeof(char)). But I don't know how to skip in an ASCII file.

No raw loops!
Reading the entire file:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream f("data.txt");
std::vector<int> v(std::istream_iterator<int>(f), {});
Skipping over the first three:
v.erase(v.begin(), v.begin() + 3);

Related

Read a file in by columns in C++

I have a file that contains numbers:
23 899 234 12
12 366 100 14
10 256 500 23
14 888 564 30
How can I read this file by column using C++? I searched YouTube but they only read file by row. If I have to find the highest value from the first column, I need to read it by columns right?
Try initialising a variable called column =0
Now when you access row iterate through column using a for loop until end of column which can be found out by no of lines in a file, then implement the operation what you are willing to do, now increase column no for going to next column.
And you can get value in form of n*vectors
Where n is no of rows
Dimension of vector is length of column
Files are storages with sequential access, so , generally you have to read everything. Essentially it's like reading from a tape. And format of your file doesn't offer any shortcuts.
But, you can fast-forward and rewind along file, using seek() if it's a file on permanent storage. It's not effective and you have to know position where to go. If your records are of same size, you can advance by fixed amount of bytes.
That is usually done with binary formats and those formats are designed to have some kind directory or other auxiliary data to help searching for proper position..
Read each line and split it by space and store the first value as highest value. repeat the steps for all rows until you reach end of file while comparing the first value again with already stored value as highest.
I don't have C++ compiler available with myself to test. it should work for you conceptually.
#include <fstream>
#include <string>
#include <iostream>
#include<sstream>
using namespace std;
int main() {
ifstream inFile("Read.txt");
string line;
int greatest = 0;
while (getline(inFile, line)) {
stringstream ss(line);
string FirstColumn;
while (ss >> FirstColumn) {
if (stoi(FirstColumn) > greatest)
greatest = stoi(FirstColumn);
}
cout << greatest << endl;
}
}

How to get line of numbers from file and ignore first number?

So, lets say we have a text.txt file with these numbers:
4 5 15 10 20
5 5 15 10 20 25
In the above example, the first numbers in the row describe how many numbers are in that row. The rest of the numbers are the numbers I am interested in (I will be sorting them in a later part of the code, but that is not where my question focuses).
My issue is, how can I best go about taking each row of numbers (ignoring the first number), placing them into a array, and then moving onto the next line and doing the same thing (placing them into an array, that will be later sorted)?
All my google searching points to doing this with strings via getline, and nothing really points to handling it with ints. Hope someone on here can help point me in the right direction.
Below is the basic code I would use to open the file:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int a;
ifstream inputfile;
//declare an input file
inputfile.open("text.txt");
while(//not sure best way to do this part)
{
//guessing I can use a for loop and place numbers in array
//based on first number in the row of numbers
}
return 0;
}
The most obvious way would probably be to read a line with std::getline, then put the string into a stringstream, and read numbers from there (ignoring the first, obviously).
I suggest the following approach:
std::string line;
// Keep reading lines of text from the file.
// Break out of the loop when there are no more lines in the file.
while (getline(inputfile, line)){
// Construct a istingstream from the line of text.
std::istringstream ss(line);
// Read the numbers from the istingstream.
// Process the numbers as you please.
}

Stopping file input when a certain word is encountered

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++);
}

reading specific integers from text file

I have a text file that contains this information.
GO
pink colour 60 5 0
pink colour 80 10 0
chocs
red colour 100 15 1
red colour 120 15 1
man
blue colour 140 20 2
fast place
Brown colour 160 20 2
Going in plane
Green colour 280 35 5
Im trying to only extract the first integer of every line. the lines that dont have any integers I can skip.
so i can skip line 1 (Go)
but i need 60 from line 2.
and 80 from line 3.
skip line 4. etc...
but i dont know how. any help is much appreciated. thanks.
You could read the file one character at a time and check if that character is a digit. If it is then continue reading until you hit a character that isn't a digit. Then ignore everything until the character is a newline. It could look something like:
char buff;
std::fstream fin("file", std::fstream::in);
buff = fin.getchar();
// Read until end of file
while (buff != file.EOF)
{
// if the char we read is a digit...
if (isdigit(buff))
{
// Continue to read characters if they are an integer (same number)
while (isdigit(buff))
{
// Store buff in some container
}
// Ignore until we hit the end of that line
fin.ignore(256, '\n');
}
}
pseudocode:
read in a line, quit at EOF
for each line
do a **string::find_first_of** for a digit
if digit not found, go to read the next line
do a **std::stoi** to convert to integer
process the integer
You can do like this:
#include <iostream>
#include <sstream>
using namespace std;
... ...
string str;
while (getline(file, str)) // read each line
{
istringstream iss(str);
int value;
string temp;
if (iss >> temp >> temp >> value) // try to read the value
{
// you got the value here
}
}

Getting input from external 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 ..