Reading/parsing multiple INTs from a String - c++

I've been reading about converting strings to integers, the "atoi" and "strol" C standard library functions, and a few other things I just can't seem to get my head around.
What I'm initially trying to do, is to get a series of numbers from a string and put them into an int array. Here is snippet of the string (there are multiple lines in the single string):
getldsscan
AngleInDegrees,DistInMM,Intensity,ErrorCodeHEX
0,0,0,8035
1,0,0,8035
2,1228,9,0
3,4560,5,0
...
230,1587,80,0
231,0,0,8035
232,1653,89,0
233,1690,105,0
234,0,0,8035
...
358,0,0,8035
359,0,0,8035
ROTATION_SPEED,4.99
The output is from my vacuum robot, a "Neato XV-21". I've gotten the output above from over a COM port connection and I've got it stored in a string currently. (As the robot can output various different things). In this example, I'm reading from a string neatoOutput which houses the output from the robot after I've requested an update from its laser scanner.
The "getldsscan" is the command I sent the robot, it's just being read back when I get the COM output so we skip over that. The next line is just helpful information about each of the values that is output, can skip over that. From then on the interesting data is output.
I'm trying to get the value of the Second number in each line of data. That number is the distance from the scanner to an obstacle. I want to have a nice tidy int distanceArray[360] which houses all the distance values that are reported back from the robot. The robot will output 360 values of distance.
I'm not fussed with error checking or reading the other values from each line of data yet, as I'll get them later once I've got my head around how to extract the current basic data I want. So far I could use something like:
int startIndex = 2 + neatoOutput.find("X",0); //Step past end of line character
So startIndex should give me the character index of where the data starts, but as you can see by the example above, the values of each number range in size from a single character up to 4 characters. So simply stepping forward through the string a set amount won't work.
What I'm thinking of doing is something like...
neatoOutput.find("\n",startIndex );
Which with a bit more code I should be able to parse one line at a time. But I'm still confused as to how I extract that second number in the line which is what I want.
If anyone is interested in about hacking/coding the robot, you can goto:-
http://www.neatorobotics.com/programmers-manual/
http://xv11hacking.wikispaces.com/
UPDATE: Resolved
Thanks for your help everyone, here is the code I'm going to work with in the near term. You'll notice I didn't end up needing to know the int startIndex variable I thought I would need to use.
//This is to check that we got data back
signed int dataValidCheck = neatoOutput.find("AngleInDegrees",0);
if (dataValidCheck == -1)
return;
istringstream iss(neatoOutput);
int angle, distance, intensity, errorCode;
string line;
//Read each line one by one, check to see if its a line that contains distance data
while (getline(iss,line))
{
if (line == "getldsscan\r")
continue;
if (line == "AngleInDegrees,DistInMM,Intensity,ErrorCodeHEX\r")
continue;
sscanf(line.c_str(),"%d,%d,%d,%d",&angle,&distance,&intensity,&errorCode); //TODO: Add error checking!
distanceArray[angle] = distance;
}

Try this (untested, so maybe minor bugs):
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
using namespace std;
int main()
{
string s("3,2,6,4\n2,3,4,5\n");
istringstream iss(s);
int a, b, c, d;
string line;
while (getline(iss,line))
{
// Method 1: Using C
sscanf(line.c_str(),"%d,%d,%d,%d",&a,&b,&c,&d);
// Method 2: Using C++
std::stringstream lineStream(line);
char comma;
lineStream >> a >> comma >> b >> comma >> c >> comma >> d;
// do whatever
}
}

You may parse the string yourself. It's simple.
code:
int ParseResult(const char *in, int *out)
{
int next;
const char *p;
p = in;
next = 0;
while (1)
{
/* seek for next number */
for (; !*p && !isdigit(*p); ++p);
if (!*p)
break; /* we're done */
out[next++] = atoi(p); /* store the number */
/* looking for next non-digit char */
for (; !*p && isdigit(*p); ++p);
}
return next; /* return num numbers we found */
}

Related

c++ if(cin>>input) doesn't work properly in while loop

I'm new to c++ and I'm trying to solve the exercise 6 from chapter 4 out of Bjarne Stroustrups book "Programming Principles and Practise Using C++ and don't understand why my code doesn't work.
The exercise:
Make a vector holding the ten string values "zero", "one", ...,
"nine". Use that in a program that converts a digit to its
corresponding spelled-out value: e.g., the input 7 gives the output
seven. Have the same program, using the same input loop, convert
spelled-out numbers into their digit form; e.g., the input seven gives
the output 7.
My loop only executes one time for a string and one time for an int, the loop seems to continue but it doesn't matter which input I'm giving, it doesn't do what it's supposed to do.
One time it worked for multiple int inputs, but only every second time. It's really weird and I don't know how to solve this in a different way.
It would be awesome if someone could help me out.
(I'm also not a native speaker, so sorry, if there are some mistakes)
The library in this code is a library provided with the book, to make the beginning easier for us noobies I guess.
#include "std_lib_facilities.h"
int main()
{
vector<string>s = {"zero","one","two","three","four","five","six","seven","eight","nine"};
string input_string;
int input_int;
while(true)
{
if(cin>>input_string)
{
for(int i = 0; i<s.size(); i++)
{
if(input_string == s[i])
{
cout<<input_string<<" = "<<i<<"\n";
}
}
}
if(cin>>input_int)
{
cout<<input_int<<" = "<<s[input_int]<<"\n";
}
}
return 0;
}
When you (successfully) read input from std::cin, the input is extracted from the buffer. The input in the buffer is removed and can not be read again.
And when you first read as a string, that will read any possible integer input as a string as well.
There are two ways of solving this:
Attempt to read as int first. And if that fails clear the errors and read as a string.
Read as a string, and try to convert to an int. If the conversion fails you have a string.
if(cin >> input) doesn't work properly in while loop?
A possible implementation of the input of your program would look something like:
std::string sentinel = "|";
std::string input;
// read whole line, then check if exit command
while (getline(std::cin, input) && input != sentinel)
{
// use string stream to check whether input digit or string
std::stringstream ss(input);
// if string, convert to digit
// else if digit, convert to string
// else clause containing a check for invalid input
}
To discriminate between int and string value you could use peek(), for example.
Preferably the last two actions of conversion (between int and string) are done by separate functions.
Assuming the inclusion of the headers:
#include <iostream>
#include <sstream>

Reading In From A File. Multiple Delimiters? C++

so I'm trying to read in some info from a file, but I've been having a really difficult time doing it. Here's the format of the file I'm trying to read in.
Name#Description
Name2#Description2 ...
NameX#DescriptionX
%
info1,info2,info3,info4 ...
infoX1,infoX2,infoX3,infoX4,
%
Keyword#Message
So what I'm trying to do is break up the first part of the code after every # and split the Name into one variable, and the Description into another variable. Then after the first % split each piece of info up into it's own variable. Finally, after the second % split those up by the # much like above, but different variables.
So I tried while(getline(inFile, str, '%') but it stops reading after the first line then goes to whatever is under the %. Having some trouble here, so any help would be appreciated!
Below is a (non-complete) structure for how you could go about this:
#include <fstream>
#include <iostream>
#include <string>
int main(void) {
const char* in_file_path = "foo.txt";
std::ifstream in_file(in_file_path);
std::string buffer = "";
while (std::getline(in_file, buffer)) {
//parse input using `#` as separator...
if (buffer.at(0) == '%') {
// get position of `%` char in stream using (e.g.) in_file.seekg
break;
}
}
// after getting position of first `%` char in stream, this loop
// will start from this position in the file
while (std::getline(in_file, buffer)) {
// parse input using `,` as separator...
if (buffer.at(0) == `%`) {
// get position of `%` char in stream using (e.g.) in_file.seekg
break;
}
}
// ... and so on for as many separations as you need until you hit end of file
}
This relies on using (for example), the seekg method of std::ifstream:
http://en.cppreference.com/w/cpp/io/basic_istream/seekg

Logic for reading rows and columns from a text file (textparser) C++

I'm really stuck with this problem I'm having for reading rows and columns from a text file. We're using text files that our prof gave us. I have the functionality running so when the user in puts "numrows (file)" the number of rows in that file prints out.
However, every time I enter the text files, it's giving me 19 for both. The first text file only has 4 rows and the other one has 7. I know my logic is wrong, but I have no idea how to fix it.
Here's what I have for the numrows function:
int numrows(string line) {
ifstream ifs;
int i;
int row = 0;
int array [10] = {0};
while (ifs.good()) {
while (getline(ifs, line)) {
istringstream stream(line);
row = 0;
while(stream >>i) {
array[row] = i;
row++;
}
}
}
}
and here's the numcols:
int numcols(string line) {
int col = 0;
int i;
int arrayA[10] = {0};
ifstream ifs;
while (ifs.good()) {
istringstream streamA(line);
col = 0;
while (streamA >>i){
arrayA[col] = i;
col++;
}
}
}
edit: #chris yes, I wasn't sure what value to return as well. Here's my main:
int main() {
string fname, line;
ifstream ifs;
cout << "---- Enter a file name : ";
while (getline(cin, fname)) { // Ctrl-Z/D to quit!
// tries to open the file whose name is in string fname
ifs.open(fname.c_str());
if(fname.substr(0,8)=="numrows ") {
line.clear();
for (int i = 8; i<fname.length(); i++) {
line = line+fname[i];
}
cout << numrows (line) << endl;
ifs.close();
}
}
return 0;
}
This problem can be more easily solved by opening the text file as an ifstream, and then using std::get to process your input.
You can try for comparison against '\n' as the end of line character, and implement a pair of counters, one for columns on a line, the other for lines.
If you have variable length columns, you might want to store the values of (numColumns in a line) in a std::vector<int>, using myVector.push_back(numColumns) or similar.
Both links are to the cplusplus.com/reference section, which can provide a large amount of information about C++ and the STL.
Edited-in overview of possible workflow
You want one program, which will take a filename, and an 'operation', in this case "numrows" or "numcols". As such, your first steps are to find out the filename, and operation.
Your current implementation of this (in your question, after editing) won't work. Using cin should however be fine. Place this earlier in your main(), before opening a file.
Use substr like you have, or alternatively, search for a space character. Assume that the input after this is your filename, and the input in the first section is your operation. Store these values.
After this, try to open your file. If the file opens successfully, continue. If it won't open, then complain to the user for a bad input, and go back to the beginning, and ask again.
Once you have your file successfully open, check which type of calculation you want to run. Counting a number of rows is fairly easy - you can go through the file one character at a time, and count the number that are equal to '\n', the line-end character. Some files might use carriage-returns, line-feeds, etc - these have different characters, but are both a) unlikely to be what you have and b) easily looked up!
A number of columns is more complicated, because your rows might not all have the same number of columns. If your input is 1 25 21 abs 3k, do you want the value to be 5? If so, you can count the number of space characters on the line and add one. If instead, you want a value of 14 (each character and each space), then just count the characters based on the number of times you call get() before reaching a '\n' character. The use of a vector as explained below to store these values might be of interest.
Having calculated these two values (or value and set of values), you can output based on the value of your 'operation' variable. For example,
if (storedOperationName == "numcols") {
cout<< "The number of values in each column is " << numColsVal << endl;
}
If you have a vector of column values, you could output all of them, using
for (int pos = 0; pos < numColsVal.size(); pos++) {
cout<< numColsVal[pos] << " ";
}
Following all of this, you can return a value from your main() of 0, or you can just end the program (C++ now considers no return value from main to a be a return of 0), or you can ask for another filename, and repeat until some other method is used to end the program.
Further details
std::get() with no arguments will return the next character of an ifstream, using the example code format
std::ifstream myFileStream;
myFileStream.open("myFileName.txt");
nextCharacter = myFileStream.get(); // You should, before this, implement a loop.
// A possible loop condition might include something like `while myFileStream.good()`
// See the linked page on std::get()
if (nextCharacter == '\n')
{ // You have a line break here }
You could use this type of structure, along with a pair of counters as described earlier, to count the number of characters on a line, and the number of lines before the EOF (end of file).
If you want to store the number of characters on a line, for each line, you could use
std::vector<int> charPerLine;
int numberOfCharactersOnThisLine = 0;
while (...)
{
numberOfCharactersOnThisLine = 0
// Other parts of the loop here, including a numberOfCharactersOnThisLine++; statement
if (endOfLineCondition)
{
charPerLine.push_back(numberOfCharactersOnThisLine); // This stores the value in the vector
}
}
You should #include <vector> and either specific std:: before, or use a using namespace std; statement near the top. People will advise against using namespaces like this, but it can be convenient (which is also a good reason to avoid it, sort of!)

read in values and store in list in c++

i have a text file with data like the following:
name
weight
groupcode
name
weight
groupcode
name
weight
groupcode
now i want write the data of all persons into a output file till the maximum weight of 10000 kg is reached.
currently i have this:
void loadData(){
ifstream readFile( "inFile.txt" );
if( !readFile.is_open() )
{
cout << "Cannot open file" << endl;
}
else
{
cout << "Open file" << endl;
}
char row[30]; // max length of a value
while(readFile.getline (row, 50))
{
cout << row << endl;
// how can i store the data into a list and also calculating the total weight?
}
readFile.close();
}
i work with visual studio 2010 professional!
because i am a c++ beginner there could be is a better way! i am open for any idea's and suggestions
thanks in advance!
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
struct entry
{
entry()
: weight()
{ }
std::string name;
int weight; // kg
std::string group_code;
};
// content of data.txt
// (without leading space)
//
// John
// 80
// Wrestler
//
// Joe
// 75
// Cowboy
int main()
{
std::ifstream stream("data.txt");
if (stream)
{
std::vector<entry> entries;
const int limit_total_weight = 10000; // kg
int total_weight = 0; // kg
entry current;
while (std::getline(stream, current.name) &&
stream >> current.weight &&
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n') && // skip the rest of the line containing the weight
std::getline(stream, current.group_code))
{
entries.push_back(current);
total_weight += current.weight;
if (total_weight > limit_total_weight)
{
break;
}
// ignore empty line
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
else
{
std::cerr << "could not open the file" << std::endl;
}
}
Edit: Since you wannt to write the entries to a file, just stream out the entries instead of storing them in the vector. And of course you could overload the operator >> and operator << for the entry type.
Well here's a clue. Do you see the mismatch between your code and your problem description? In your problem description you have the data in groups of four lines, name, weight, groupcode, and a blank line. But in your code you only read one line each time round your loop, you should read four lines each time round your loop. So something like this
char name[30];
char weight[30];
char groupcode[30];
char blank[30];
while (readFile.getline (name, 30) &&
readFile.getline (weight, 30) &&
readFile.getline (groupcode, 30) &&
readFile.getline (blank, 30))
{
// now do something with name, weight and groupcode
}
Not perfect by a long way, but hopefully will get you started on the right track. Remember the structure of your code should match the structure of your problem description.
Have two file pointers, try reading input file and keep writing to o/p file. Meanwhile have a counter and keep incrementing with weight. When weight >= 10k, break the loop. By then you will have required data in o/p file.
Use this link for list of I/O APIs:
http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx
If you want to struggle through things to build a working program on your own, read this. If you'd rather learn by example and study a strong example of C++ input/output, I'd definitely suggest poring over Simon's code.
First things first: You created a row buffer with 30 characters when you wrote, "char row[30];"
In the next line, you should change the readFile.getline(row, 50) call to readFile.getline(row, 30). Otherwise, it will try to read in 50 characters, and if someone has a name longer than 30, the memory past the buffer will become corrupted. So, that's a no-no. ;)
If you want to learn C++, I would strongly suggest that you use the standard library for I/O rather than the Microsoft-specific libraries that rplusg suggested. You're on the right track with ifstream and getline. If you want to learn pure C++, Simon has the right idea in his comment about switching out the character array for an std::string.
Anyway, john gave good advice about structuring your program around the problem description. As he said, you will want to read four lines with every iteration of the loop. When you read the weight line, you will want to find a way to get numerical output from it (if you're sticking with the character array, try http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/, or try http://www.cplusplus.com/reference/clibrary/cstdlib/atof/ for non-whole numbers). Then you can add that to a running weight total. Each iteration, output data to a file as required, and once your weight total >= 10000, that's when you know to break out of the loop.
However, you might not want to use getline inside of your while condition at all: Since you have to use getline four times each loop iteration, you would either have to use something similar to Simon's code or store your results in four separate buffers if you did it that way (otherwise, you won't have time to read the weight and print out the line before the next line is read in!).
Instead, you can also structure the loop to be while(total <= 10000) or something similar. In that case, you can use four sets of if(readFile.getline(row, 30)) inside of the loop, and you'll be able to read in the weight and print things out in between each set. The loop will end automatically after the iteration that pushes the total weight over 10000...but you should also break out of it if you reach the end of the file, or you'll be stuck in a loop for all eternity. :p
Good luck!

Reading input into dynamically-sized array

What I've been trying to do, is read a line from stdin and split it, by using whitespace as seperators.
Let's say I have this as input:
2
1 2
3 4
The first line gives me the amount of lines I'd like to read, they're all lines with integers seperated by an unknown amount of whitespace (i.e. could be 1 space, but it could also be 10 spaces).
The thing I've been trying to do is reading those lines into dynamically sized arrays of integers.
This was extremely easy in Python:
foo = raw_input()
array = foo.split()
or even shorter:
foo = raw_input().split()
However, because of the circumstances, I have to learn the beauty of C++.
So I tried to create something akin to the above Python code:
#include <iostream>
using namespace std;
int lines;
int *array;
int main() {
cin >> lines;
for (int line = 0; line < lines; line++) {
// Something.
}
}
I don't seem to know a way to split the line of input. I know that std::cin reads until it reaches a whitespace. However, I can't seem to think of something to count the amount of numbers on the line...
A little nudge into the right direction would be appreciated, thanks.
so given all you wanted is a nudge, here are a couple of hints..
std::getline() - allows you to read from a stream into a std::string.
You can then construct a std::istringstream using this string which you've just read in. Then use this stream to read your ints
for example:
std::string line;
if(std::getline(std::cin, line))
{
std::istringstream str(line);
int lc;
if (str >> lc) // now you have the line count..
{
// now use the same technique above
}
}
oh and for your "dynamically sized array", you need to look at std::vector<>
In C++ you can access characters in a string with [], just as if that string were an array. I suggest you read a line from cin into a string, iterate over the string with a for loop and check each character to see whether it is whitespace. Whenever you find a non-whitespace character, store it in your array.