Problem with getline in C++ programming

In summary, the conversation discusses a problem with reading numbers from a csv file in C++. The use of getline to retrieve strings and convert them to integers seems to discard the last cell in the file. The attempted solution involves using a while loop and stringstream to convert the string to an integer and store it in an array. However, the issue with the last cell remains unresolved. There is a suggestion to try using getc instead of getline.
  • #1
khotsofalang
21
0

Homework Statement



I am solving a problem in which I am reading numbers from cells in a csv file, I used getline to get strings from the csv file then converted the string to an integer... but the getline seemingly discards the last cell in the csv file


Homework Equations



this my C++ code:
if (input_file.good()){
array= new int;
while(!input_file.eof()){getline(input_file,number,',');//input filename is istream
//problem seems to be with the getline discarding the last cell
if(input_file.good()){

//otherwise everything is okay except i nid that number in last cell

cout<<number<<endl;
stringstream convert(number);
convert>>num;
array=num;
// cout<<num;
i++;}}}

The Attempt at a Solution



I attempted the solution as above, please let me know if there is an effecient way to get all data from the file
 
Physics news on Phys.org
  • #2
I am not quite sure why this is happening (I mostly use C, almost never getline) but have you tried getc?
 

FAQ: Problem with getline in C++ programming

What is getline in C++ programming?

getline is a function in C++ that is used to read input from an input stream until a specified delimiter is encountered. It is commonly used to read string inputs from the user.

2. Why is getline not working in my code?

There could be several reasons why getline is not working in your code. Some common reasons include not properly including the necessary header files, not properly declaring the input stream, or not providing the correct arguments for the function.

3. Can getline be used to read inputs of different data types?

No, getline is specifically designed to read string inputs. If you need to read inputs of different data types, you can use other input functions such as cin or scanf.

4. How can I specify a custom delimiter for getline?

You can specify a custom delimiter for getline by passing it as a third argument in the function. For example, getline(cin, input, '#') will read input from the user until the # character is encountered.

5. Is getline affected by whitespace characters?

Yes, by default, getline will ignore all leading whitespace characters and will stop reading when it encounters the first whitespace character. This behavior can be changed by using the noskipws manipulator before calling getline.

Similar threads

Replies
16
Views
2K
Replies
2
Views
2K
Replies
3
Views
1K
Replies
2
Views
3K
Replies
8
Views
2K
Replies
9
Views
3K
Replies
15
Views
2K
Back
Top