Re-setting an istringstream object - c++

When I run this code:
for (int i = 0; i < indexArray.size(); i++) {
iss.str(indexArray.at(i));
iss>>one;
iss>>two;
iss>>three;
cout<<one<<" "<<two<<" "<<" "<<three<<" "<<"\n";
}
the istreamstream (iss) remains the same with every iteration. (The file is read into an vector at the beginning of the program. Yes, I checked to make sure the array had the corresponding data.)
In other words, I get this output:
12345 1 0
12345 1 0
12345 1 0
whereas the file/vector actually says:
12345 1 0
12346 1 25
12543 1 50
I've tried various traces and can't pinpoint the problem. Thanks!

You should call iss.clear(); before iss.str(indexArray.at(i)); to clear the EOF flag when reusing istringstream.

Related

How to read character by character from a file to a 2D array

I'm trying to read character from a text file that looks like this. The '-' are supposed to be converted to zeros and the 'x' are supposed to be converted to ones
3
3
-x-
xx-
--x
I'm able to read the first two integers using a seperate function but when I use this method to copy it over I get a 3x6 2d array with all zeros. the output is
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
To read character by character from a file, you have some options.
Character by character
char c;
ifstream data_file("my_file.txt");
while (data_file >> c)
{
Do_Something_With_Character(c);
}
By text line
From your input data example, you may want to read text line instead:
std::string text;
ifstream data_file("my_file.txt")
while (getline(data_file, text))
{
for (int index = 0; index < text.length(); ++i)
{
Do_Something_With_Character(text[index]);
}
}
Note: The above examples are generic for reading data. They do not parse the OP's input file.

All output at last-C++ compiler

This question might sound stupid but I really want to know that How do I get all the output at last after inputting all the input.Example,For input
3
14
7
6
Output suppose will be
0
0
1
0
But compiler is giving output something like
3
0 14
0 7
1 6
0
Which doesn't look good,so I want to get output like the one we get in IDEONE(i.e all at the last).Is this possible ?IF yes,than please let me know
I'd suppose that you read the input int by int, and the output comes as soon as another int is read, while to achieve the desired behavior you have to read them all first and then process.
std::vector<int> ints;
while (std::cin)
{
int x;
if (std::cin >> x)
ints.push_back(x);
}
for (int x : ints)
{
// do what you want with x
}
Note that the problem is definitely not the compiler, it's just how most terminals work - both standard input stream (stdin) and standard output stream (stdout) are linked with the text that you type/see in the terminal.

C++ Converting a text file list with numbers and words into an integer 2D array

I have a basic text file which has one entry per line, most entries are are numerical, however there are a few lines with the word and (evenly spaced) in them. Here is an example of one such spacing between and :
<event>
4
0
0.1005960E+03
0.2722592E+03
0.7546771E-02
0.1099994E+00
21
-1
0
0
501
502
0.00000000000E+00
0.00000000000E+00
0.17700026409E+03
0.17700026409E+03
0.00000000000E+00
0.
-1.
21
-1
0
0
502
503
0.00000000000E+00
0.00000000000E+00
-0.45779372796E+03
0.45779372796E+03
0.00000000000E+00
0.
1.
6
1
1
2
501
0
-0.13244216743E+03
-0.16326397666E+03
-0.47746002227E+02
0.27641406353E+03
0.17300000000E+03
0.
-1.
-6
1
1
2
0
503
0.13244216743E+03
0.16326397666E+03
-0.23304746164E+03
0.35837992852E+03
0.17300000000E+03
0.
1.
</event>
What I need to do is create a numerical matrix (using only the numerical values) where each column holds all the data values between each separate instance of and .
This is what I have so far:
using namespace std;
int main()
{
vector <string> data;
string str;
ifstream fin("final_small.txt");
while (fin >> str)
{
data.push_back(str);
}
fin.close(); // Close the file.
int N = data.size();
int matrix[13][19];
for (int i = 0; i < 13; i++) {
for (int j = 0; j < 19; j++) {
matrix[i][j] = data[i];
}
}
}
Obviously this is a huge work in progress. First of all, I read the text file in to a vector, which can not be of type int because of the words. This then causes problems later on when I try to input it into the matrix.
Does anyone have any suggestions?
Thanks in advance!
In C++11, use std::stoi to convert a string to an int. Note that std::stoi will throw an exception of type std::invalid_argument if the conversion cannot be performed.
Could you give some example inputs? What you could do is iterate through each line and only convert characters that are numbers. You can check this with the stdlib function isdigit() which you can see here. You can then use atoi() for numerical conversion. Hope this helps!

Ifstream getting information from a textfile

At the moment I'm trying to get to create a race track that has all of the textures on the ground loaded via a textfile. An example is this:
0, 0, 1, 1, 1, 1, 0, 0
0, 1, 0, 0, 0, 0, 1, 0
0, 0, 1, 1, 1, 1, 0, 0
The ground itself is simply a grid.
At the moment the code I have to get information from text file is as follows:
string line;
ifstream myfile ("track1.txt");
if (myfile.is_open())
{
while ( !myfile.eof() )
{
getline( myfile, line, ',');
if (line == '0')
{
const wstring textureFileName=TEXT("crate.jpg");
}
myfile>>line;
}
myfile.close();
}
When I build this code, how ever I get the following error:
binary '==' : no operator found which
takes a right-hand operand of type
Then if I change the double equals sign to a single I get the following error:
error C2451: conditional expression
of type 'std::basic_string<_Elem,_Traits,_Ax>'is illegal
'char' (or there is no acceptable
conversion)
Is there something I'm missing that is causing the error?
Sorry for my lack of proper detail.
Thank you chaosTechnician. Will the val work on multiple lines in the text file?
Like this
0 0 1 1 1 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 1 1 1 0 0
I mean, is there anything else I need to type to get the computer to realise the line has ended?
You're trying to compare a string to a char:
line == '0'
instead, try:
line[0] == '0'
or:
line == "0"
First, I strongly suggest using the code formatting in your post to make it easier to read...
Also, the easiest way to see if it's written correctly would be to compile it and run it. :)
If your text file is 0,0,0,0,0,0,0,0,0,0 (everything on one line), then getline(myfile, line); will read it all in with your first read--it's all on one line. Here's a link to how getline() works. If you were to use a comma as the delimeter (by passing a comma as the third argument: getline(myfile, line, ',');) it's much more likely to do what you want. But, if you want to just read each line, why put them on the same line separated with a comma when you could just put each on its own line? Is there a specific reason you're doing it that way?
Additionally, if line is a string, if(line == 0) won't check what you want it to check. You'd need to convert line to a int to compare values.
If you want to be using ifstream and the values in the file will be integers, I'd suggest something akin to this:
int val;
ifstream myfile("track1.txt");
while(myfile >> val)
{
//Use the value in here
}
Then your file can be as simple as this:
0 0 0 0 0 0 0 0 0 0
Hope this helps.
To expand on chaosTechnician answer the ifstream does not see lines.
every time you call myfile it will read the next value irrespective of its location.
that means that it would read 0 0 0 0 and
0
0
0
0
as the same thing.
the way I use it in my code is to put different data on diffident lines for example
50 //race length
0 0 0 //first square of each lane
0 1 0 //second lane and so on
but it would function exactly the same if it was
50 0 0 0 0 1 0
By knowing what order the information will be read in you can read it into variables at load time and manipulate them as the game goes on.
Good luck with your project
edit:
I use c++ an directx 9.c so this method should work for you.
If you're concerned about keeping relative spatial data (i.e., rows/columns of each 'tile') intact and you're limiting yourself to ascii files, you might as well just forgo any issues with delimiting or reading invalid input by switching to chars.
Let's say this is your file:
a6sgb1
dsj26s
l8h9h4
34gpoy
And then do do the following to parse it (after testing reading a line from std::getline() through std::stringstream, std::get(), and just plain iterating through a std::string from std::getline() on my development machine, I found the first to be fastest - your mileage may vary. I'll supply all three):
stringstream
ifstream strFile("test.txt");
string line;
int row(0);
int col(0);
while(getline(strFile, line)) {
stringstream ss(line);
char ch;
while(ss >> ch) {
switch(ch) {
// your code
}
++col;
}
++row;
}
line iteration
istream lineFile("test.txt");
string line;
int row(0);
while(getline(lineFile, line)) {
int len(line.length());
for(int col = 0; col < len; ++col) {
switch(line[col]) {
// your code
}
}
++row;
}
individual char parsing
ifstream chFile("test.txt");
char ch;
int row(0);
int col(0);
while(chFile.get(ch)) {
switch(ch) {
case '\n':
++row;
break;
// your code
}
++col;
}
Someone else mentioned questions like this should probably be on stackoverflow, I agree.

problem in understanding the code

i = 0;
while (fscanf(fp, "%f %f %d", &x[i], &y[i], &outputs[i]) != EOF) {
if (outputs[i] == 0) {
outputs[i] = -1;
}
i++;
}
patternCount = i;
I dont understand the meaning of this line from the above code:
if (outputs[i] == 0) {
outputs[i] = -1;
What does it represent. The Output is a matrix or vector.??
The refrence of the code is:
Perceptron learning algorithm not converging to 0
I have a output file that has 3 columns:
1 0 0
0 0 1
0 1 0
So it a vector file??
outputs is defined as a one-dimensional array containing integer values..
float x[208], y[208];
int outputs[208];
Each index in the array can be seen as corresponding to a line read in the data file.
i x y outputs
--------------------------------------
0 | -8.818681 3.025210 1
1 | 3.653846 -2.969188 0
2 | ... ... .
.. | ... ... .
208 | -6.565934 -4.649860 1
Where if i == 0 then
x[0] == -8.818681
y[0] == 3.025210
outputs[0] == 1
The wonderful code and information posted by user Amro explain the limits and function of outputs.
"...bias term, i.e. a third weight component connected to an input of value 1. (+1/-1)
"
Values for outputs in the data file have been assigned one/zero values.
Therefore the code in question checks to see if the value for outputs read in from the file is equal to zero and re-assigns to a -1.
if (outputs[i] == 0)
outputs[i] = -1;
as far as I can tell, the code is reading from a file, and the file is supposed to have a repeated pattern, each pattern consists of 3 numbers.
Your loop copy the first number in each pattern to x, the second to y, and the last to outputs. However whenever the third number is a zero, it is changed to -1.
patternCount will store the number of pattern read in the file
A perceptron is a term from artificial intelligence/neural networks. It operates in much the same way as a single neuron is supposed to operate in the brain.
It has a number of inputs and a single output.
All this file is doing is specifying what the output should be for a given set of inputs. That's why the x/y and output are named differently.
As to why it's morphing the output from 0 to -1 (that's all it's doing by the way: changing zeros in the third file column into negative one), I'm not sure. The outputs of perceptrons almost invariably feed into other perceptrons so passing a -1 to something that expects 0 or 1 is an ... interesting ... idea.