-2

I am trying to find a solution for the error that the c++ compiler (codeblocks) keeps showing to me,I searched for answers on the net but none of them seemed to be helpful. I have a txt file in which there are numbers,each of them is written in a line. What i want is to read each number(line by line)and store it in a variable after converting it from string to float. This my code

#include <fstream>
#include <sstream>
#include <string>
#include <iostream>

float z;   
int j=0;
stringstream s; 
const ifstream fich1; 
fich1.open("test.txt",ios::in);     
if(!fich1)
{ 
    cerr<<"could not open the file";
    EXIT_FAILURE;
};
else const string ligne1;
while((!fich1.eof())
{ 
    if(j!=i)
    {
        j++;
        getline(fich1,l1); // the first error is: no matching function for call to ‘getline(const ifstream&, const string&)
    else if(j == i)
    {   
        fich1>>s; // the second error is: ambiguous overload for ‘operator>>’ (operand types are ‘const ifstream {aka const std::basic_ifstream<char>}’ and ‘std::stringstream {aka std::basic_stringstream<char>}’)
        z=(float)s; // I couldn't find a clear answer to convert from string to float
    }
}

if anyone wants to ask any question about the code to make it clearer may ask it please,I am waiting for your answers as well as your questions :)

mpross
  • 76
  • 8
farhawa
  • 8,406
  • 16
  • 37
  • 80

3 Answers3

2

After the edit, I am able to read some code, but still I am suggesting the example I have below, since I am see scary things, like an EOF inside a loop!

Oh also, if you have C++11 support, then you could use std::stof.


You could try this (since your post is not readable), which reads a file line by line and stores every float number in a vector:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>

int main() {
  std::vector<float> v;
  std::string rec_file = "test.txt";
  std::string line;
  std::ifstream myfile(rec_file.c_str());
  if(myfile.is_open()) {
    while(std::getline(myfile,line)) {
      if(!line.empty())
        v.push_back(atof(line.c_str()));
    }
    myfile.close();
  } else {
      std::cerr << "Unable to open file";
  }
  for(unsigned int i = 0; i < v.size(); ++i)
    std::cout << v[i] << std::endl;
  return 0;
}

with the test.txt to be:

1.2
2.3
3.4
4.5
5.6
6.7

and the output:

1.2
2.3
3.4
4.5
5.6
6.7
Community
  • 1
  • 1
gsamaras
  • 66,800
  • 33
  • 152
  • 256
  • Is it necessary to use vector? I just need one variable in which I store the number(which is "z" in my code) .Because i need to compare it to an other constant number,and then I replace the content of z by the next number in the next line to compare it also. – farhawa Aug 06 '15 at 16:15
  • @farhawa no of course. It was just an example. So, do `if(!line.empty()) z = atof(line.c_str());`. Hope this helps! :) – gsamaras Aug 06 '15 at 17:41
  • 1
    Actually your answer was useful Thank you very much :) ! – farhawa Aug 07 '15 at 08:09
0

Your ifstream shouldn't be constant, as getline alters the ifstream.

To convert from char array to float use atof(chararray)

To convert from string to float you could use atof(string.cstr())

Ethan Fine
  • 489
  • 3
  • 8
  • actually I wrote fich1.getline(l1) and it is always the same error,may be because of the variable l1 which is declared as string and you said that it must be "a char array of length long enough to hold the line" ? – farhawa Aug 06 '15 at 16:19
  • I can only asnwer the question you actually ask. If you wrote fich1.getline(l1), then it should be in your question, not in a comment on my answer. – Ethan Fine Aug 06 '15 at 16:59
  • @EthanFine: Note that there is a global [std::getline](http://en.cppreference.com/w/cpp/string/basic_string/getline), which is actually the function of choice here. – DevSolar Aug 06 '15 at 18:17
  • You're right. I edited. I don't know how I missed that, I did a check to be sure but apparently I wasn't thorough enough. The other answers to this question are much better anyway, so maybe I should just delete this one? – Ethan Fine Aug 06 '15 at 18:22
  • You could use `atof`, but really you shouldn't. `atof` fails silently when the whole string does not convert. – user4581301 Aug 07 '15 at 00:23
-1

You cannot use const here. But that's not your only problem.

#include <fstream>
#include <sstream>
#include <string>
#include <iostream>

Looks good.

float z;   
int j=0;
stringstream s; 

There should be some int main() { here, because that is the function called by the runtime when a C++ executable starts. This isn't Bash or Perl where execution simply picks up at the first statement.

And you either need to write using namespace std; or prefix identifiers like stringstream as std::stringstream.

const ifstream fich1; 

This won't work. ifstream must not be declared const. (This is actually the explanation for the errors you encountered, but you made many more.)

An input file stream is an object with complex inner state, like where in the file you're currently at, error flags etc.; this inner state is changing so const ifstream simply won't work.

fich1.open("test.txt",ios::in);     

This can't work either due to const, just like all the other operations on fich1 you're doing further down.

if(!fich1)
      { cerr<<"could not open the file";
      EXIT_FAILURE;
     };

EXIT_FAILURE is a symbolic constant for a return value. As-is, you could just as well have written 0;. If you expected this to end your program, you're wrong.

      ;

The semicolon ends the if.

      else

Since the if has ended, this is a syntax error.

         const string ligne1;

If you declare a string const, you cannot assign to it. Besides, even if the else were correct, that semicolon would have ended the else, because you didn't add braces (as you should always do, even with one-line blocks, because it's so easy to make mistakes otherwise).

The way the code continues, I very much doubt this was your intention. (Some discipline with the indenting makes this kind of mistakes really easy to spot.)

         while((!fich1.eof())

How to read until EOF from cin.

         { if(j!=i)
             {j++;

Do some proper indenting, will you? Besides, no i has been declared at this point.

         getline(fich1,l1);

I assume l1 is the string you declared earlier as ligne1. (Since that happened inside the else, ligne1 is no longer in scope, but I'll let that one pass since you obviously intended the while to be inside the else block.)

Anyway, this can't work because both your ifstream and your string are constant, i.e. cannot be changed. This does not make sense, and thus getline() was not defined for const parameters.

             else if(j == i)

Since you didn't close the brace of the if statement above, this is a syntax error as well. Again, proper indenting discipline would have made this immediately obvious.

             {   fich1>>s;

I very much doubt there exists an operator>>() for const ifstream, so I am not surprised you get an error here.

                 z=(float)s;

You're trying to cast (C style, too...) a stringstream object to a float number? What do you expect the result might be? It will definitely not be the 3.14 or whatever you've written into test.txt...

               }
}

Lost track of your braces. This code is FUBAR, I didn't even check if it makes sense semantically once all the errors are fixed, and I suspect you're pulling some elaborate troll prank here. If that isn't the case, I suggest you take another good look at whatever textbook you're using to learn C++, because you got a good many things very wrong.


Purely style-related advice: fich1, ligne1... don't use localized (non-English) identifiers. It just adds another problem when communicating about your code. (And this is coming from a non-native English speaker.)

Community
  • 1
  • 1
DevSolar
  • 59,831
  • 18
  • 119
  • 197
  • I really appreciate your time for reading my code.I am a beginner in C++ programming but I am sure that I don't make mistakes as forgetting to write main()! But actually this is an extract of a whole code in which I mixed the main part and the file class.cpp to just show you where I got the error,If you know why I got the getline error and why the operator << doesn't not exist for ifstream,knowing that i found it written in some forums.Would you just answer me,that's all what it takes – farhawa Aug 06 '15 at 16:57
  • @farhawa: I judge by the code you posted, which is short, [but neither self-contained *nor* compilable](http://sscce.org/), at which point you might say "sorry" and post better code, but certainly not "just answer me" when you quite obviously didn't even bother to read my answer in full. Your errors are explained quite plainly right there. (And you aren't *using* `ifstream::operator<>`, and **I did explain why `getline` and `>>` fail, right there in the first line**.) Downvote because reading fail, well done. – DevSolar Aug 06 '15 at 18:08