Useing user imput to determine the file name to scan in

I am trying to write a program that is dependent on the model number that the user types in, and then the model number is the name of the file that I need put in an array

This is what I have so far:

int z;
float scale1[z];
int m=1;
const string productnumberfinal=userinputpro;
string filename;
filename= userinputpro+".txt";
ifstream myfile2(filename);
while(myfile2>>m){
scale1[z]=m;
cout<<scale1[z]<< endl;
i++;
}
Try to post the full code and use the formatting "/code/" tags so it'll be easier to follow along. As it is, it's very confusing to follow. If the program is dependent on user input, then you need to create a prompt and read in the model number, as you have it there is no prompt.

1
2
3
string modelnumber;
cout << "What is the model number?" << endl;
cin >> modelnumber;


Also why do you create a constant string variable?
Last edited on
1)opps sorry this is my first time on this site..
2)I have done all of that earlier in my code...
3) I was just trying what ever I could
4)I will have a document that needs to be read into the array but the model number that the user inputed
5) I dont have it currently it is on my other computer sorry :/
ifstream myfile2(filename);? I think that may be your problem. I would do this:
1
2
ifstream myfile2; //Creating myfile2
myfile2.open(filename); //Calling a function contained by myfile2 
THANK YOU I will try this as soon as I am able to get back to my code... and add anything if I have problums
I am getting an error that is saying:

95 no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::open(std::string&)'
Ah I forgot about that. It doesn't accept strings, but chars rather. Here, this should work.
1
2
3
4
5
6
7
8
			char input[100];
			cin >> input;
			ifstream myfile2;
			myfile2.open(input);
			if(!myfile2.good())
			{
				cout << "Fail";
			}
Last edited on
Ok that works but on to the input I need to add a .txt how would I add that
1
2
3
4
5
6
7
8
9
10
11
12
char *filename=new char[userinputpro.size()+1];
    filename[userinputpro.size()]=0;
    memcpy(filename,userinputpro.c_str(),userinputpro.size());
    ifstream myfile2;
    myfile2.open(filename);

        if(!myfile2)
        {
            cout<<"Error Code 2"<<endl;//error opening the scales file
                system("pause");
            return -1;
            }
Last edited on
Using a character array is not the best way to approach this problem (and, in fact, it's actually a terrible terrible solution...).

http://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream
http://en.cppreference.com/w/cpp/string/basic_string/c_str

As you can see, basic_ifstream provides a constructor that takes a cstring as it's argument (aka: a pointer to an array of characters). Your character array works because character arrays get casted to char* when passed to a function taking char* as its argument. Fortunately, there is a better solution: std::string::c_str is a much better alternative:

1
2
std::string my_file{"filename.txt"};
std::ifstream in{my_file.c_str(), std::ios::in};


ALSO: your above code has a memory leak at line 11. If you can't work with pointers properly, please don't use them. The Standard Template Library provides many facilities, including smart pointers, that allow you to avoid memory management.

http://en.cppreference.com/w/cpp/language/raii
Last edited on
1. Note that the C++11 version of fstream::open() does have an overload that accepts string, so with new compilers you won't have a problem. (Do you which compiler and version you're using?)

(Edit: 2 is just repeating part of what IWishIKnew said...)

2. Before that, you just need to use string::c_str() to get hold of a const char* pointer to the contained string.

(assuming usual includes...)

string filename;

(ask user for file name storing it in string...)

1
2
3
ifstream myfile2; //Creating myfile2
myfile2.open(filename.c_str()); //Calling a function contained by myfile2
// now using .c_str(); 


(The ios::in (or std::ios::in) parameter in IWishIKnew's example is optional; this flag is implicit when using an ifstream, as opposed to opening an fstream in read mode.)

3. IWishIKnew's approach, using the constructor which takes the filename and opens the file, is better form than using the default constructor and then opening explicitly.

4 This is not good code :-(

1
2
3
4
    char input[100];
    cin >> input;
    ifstream myfile2;
    myfile2.open(input);


because cin >> does not care how many chars you give it to extract into your array. So you could overrun if given a stupidly large file name. If for some reason you need to use a buffer, use istream::get() instead:
http://www.cplusplus.com/reference/istream/istream/get/

1
2
3
    char input[100];
    cin.get(input, 100); // get up to 100 chars
    ifstream myfile2(input);


5. I agree with IWishIKnew that the new an array, memcpy, etc approach is TERRIBLE!

Andy
Last edited on
1) I fixed the leak
2) Thank you for helping me with that but I still need to add a .txt to filename.
For example if the user who already has imputed the value lets say ERK100 I need this part of the program to open ERK100.txt
filename= userinputpro+".txt";
You already have this in your code. You should test your file object to make sure it is opened before performing any operations on it.
THANK YOU (ALL OF YOU I GOT IT :))
(Edit: the post that this was a response to has gone AWOL (about failing to open file even though it's in the right place...)

Check that your program is trying to open the file in the right place.

This program shows how to get your program to report where it's looking. It's coded for Windows so will need tweaking to work with Linux, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <direct.h> // if building for Linux, use <unistd.h> instead
using namespace std;

int main()
{
    string filename = "test.txt";
    string filepath;

    char cwd[256] = {0};
    _getcwd(cwd, 256); // if building with GCC, etc use getcwd() instead

    filepath = cwd;
    filepath += "\\"; // use "/" with Linux, etc
    filepath += filename;

    cout << "cwd      = " << cwd      << "\n"
         << "filename = " << filename << "\n"
         << "filepath = " << filepath << "\n";

    return 0;
}


Andy
Last edited on
Topic archived. No new replies allowed.