Hi guys,

I'm new to C++ and I'm doing a small project, I got a little problem with reading a specific number from a text file.
for example:

size 2 3

I want my program to read the 2 to a and the 3 to b. Also I want the user to input the store number and then I can look for this number in my file to give him all the information he wants.
fro example;

Store 1
Available Soft drinks: 24
Pepsi/ 7up: 12/12

Store2
info..

I want to go the required store and show the user the information he wants.

Attached is what I have done so far though it's still not working.
I really appreciate ur help.
thanks :)

#include <iostream>
#include <fstream>
using namespace std;

int main () {
	int m, n, x,y, store;
	ifstream file;
	file.open ("file.txt");
	if (!file1){
		cout << "Unable to open file"; // if file doesn't exist
		exit(1);
	}

        m = file.get();
	n = file.get();
	cout << "Enter the store number you want  to know about it? " << "\n";
	cin >> x;
	fscanf(file, "%store", x); 
        cout << "You have: " << y << "Pepsi" << "\n";
	cout << "You have: " << y << "7yp" << "\n";

You have this posted as a code snippet, but it looks like a regular forum thread (snippets are when you don't need help and you know how to do something and want to share your code with others).

I don't know what the "size 2 3" part has to do with the other part of the program or whether it is two separate tasks. Regardless, don't use "get" here; use the >> operator:

If this is your input file and file is your ifstream:

size 2 3
string aString; // used to store the word "size"
int a, b; // stores 2 and 3
file >> aString;
file >> a;
file >> b;

a now stores 2 and b stores 3.

As to your other question, you'll probably need to elaborate more. What exactly does the file look like? You have some dots in there. You'll want to post more of the file so it's clear what it looks like (maybe the first three or four records).

Edited 6 Years Ago by VernonDozier: n/a

Thank VernonDozier!

The second part of my project is to ask the user to enter a store number (cout << "enter the store number!"), and then I have to find the store in the text file and give the users all the information related to this store.

I defined x to be the input, cin >> x, but I still don't know how to look for the specified store and print the information of this store to the user.
for example:
if he enters 6 and store 6 is written in my text file as:
store 6
Address: 1233 W 6th St.
Telephone/Fax: 6666666/5555555

I have to print each of the above information in a different line including the phone number and the fax number.

I really appreciate ur help and please can u tell me a good book or website that can help me improving my programing skills. Thanks again!

Thank VernonDozier!

The second part of my project is to ask the user to enter a store number (cout << "enter the store number!"), and then I have to find the store in the text file and give the users all the information related to this store.

I defined x to be the input, cin >> x, but I still don't know how to look for the specified store and print the information of this store to the user.
for example:
if he enters 6 and store 6 is written in my text file as:
store 6
Address: 1233 W 6th St.
Telephone/Fax: 6666666/5555555

I have to print each of the above information in a different line including the phone number and the fax number.

I really appreciate ur help and please can u tell me a good book or website that can help me improving my programing skills. Thanks again!

You are welcome. You have a few options. Pretty much all of them involve knowing the exact layout of the input file. That's why I suggested posting a little more of it. You have to know the following:

  1. The relevant information in the file.
  2. The irrelevant information in the file.
  3. The file's layout (what is where), including delimiters.
  4. Your experience level (i.e. if you know what a "struct" or "class" is, you would likely use them. If not, you won't. I am assuming you have not used structs yet. Ditto, possibly, for stringstreams. The toolset you bring to the table helps tell you how to approach the problem.).
  5. User input.
  6. Desired output for this input.

To take your example:

store 6
Address: 1233 W 6th St.
Telephone/Fax: 6666666/5555555

Your layout is this:

  1. The information is on three lines.
  2. First line is the word "store" followed by a space, then the store number.
  3. Second line is the word "Address", followed by a colon, then a space, then by the address.
  4. Third line is "Telephone/Fax", followed by a colon, then a space, then the telephone number, then a colon, then the fax number.

One approach is this:

  1. Ask user for store number.
  2. Create a string with that store number: ("store 6").
  3. Open the file and read a line at a time using "getline".
  4. Compare the line you read to "store 6".
  5. If it isn't "store 6", move on to the next line, read it in, do the same thing again till you find it.
  6. When you find it, read the next two lines and display them.
  7. Close the file.

Tools you may use for this:

string library
itoa function to change a number to a C-Style string
(warning : not all compilers have this)
atoi function to change a C-Style string to a number.
string constructor (make a C-String) into a string

"getline", "compare", "substr", and "find" from the string library above.

Here's your main stopping place for the libraries and functions:

http://www.cplusplus.com/reference/

You'll use "string", "fstream", "cstdlib", and "cstring" possibly.

It has a good tutorial section too.

http://www.cplusplus.com/
http://www.cplusplus.com/doc/tutorial/

As for other resources, see the pinned threads at the top of the C++ forums, particularly the "C++ Books" link.


So my advice is, first, see if your compiler has itoa. Compile and run this program (posted verbatim from the itoa link. Make sure it compiles and runs and you get the output in the link.

http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

If it works, you can use my suggestions above. If not, you'll have to do something slightly different (or write your own itoa function).

/* itoa example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char buffer [33];
  printf ("Enter a number: ");
  scanf ("%d",&i);
  itoa (i,buffer,10);
  printf ("decimal: %s\n",buffer);
  itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);
  return 0;
}

Note the lines above:

#include <stdio.h>
#include <stdlib.h>

Those are C libraries. For the C++ libraries, take the ".h" off the end and stick a "c" in front.

#include <cstdio>
#include <cstdlib>

Your C++ compiler will compile it fine either way. Just pointing out that they are actually the same libraries.

Comments
Great post!

Thank you but I still can not understand how to find the store number in the file.
The user will enter only the store number which is in this case from (1-12) because I have 12 stores in my text file with different information.
how can I look for the word store and the number which was entered by the user?
should I use:

boot getline(store, cin); // 
cout << "the adress is:" << file << "\n"; // would this read the whole address?
cout << "the phone number is: " << file << "\n";
cout << "the fax number is: " << file << "\n";

Well, this my first time to take a C++ course so I really don't know that much. I'm using also Xcode bcoz my OS is MAC.

The layout of me text file is:

Store 1
Address: 1233 W 6th St.
Telephone/Fax: 6666666/5555555

Store 2
Address: 4444 E 29th St.
Telephone/Fax: 12121212/54545454

Store 3
Address: 2345 S 8th St.
Telephone/Fax: 7777777/4444444

The rest of the file is like this till store 12.

Thank you again.

Let's say you are trying to find Store 3. Here's some code to get you started. There's more for you to do, but hopefully this will get you moving in the right direction.

Did you compile the itoa program to see whether you had it?

#include <fstream>
#include <iostream>
#include <string>
using namespace std;


int main ()
{
    ifstream file;
    file.open ("file.txt");
    if (!file)
    {
        cout << "Unable to open file"; // if file doesn't exist
        exit(1);
    }

    /* ask the user to enter a store.  Use itoa, string functions,
       whatever, to end up with a string containing "Store 3".
       For this program, this part is skipped
    */

    string storeString = "Store 3";  // we're looking for this
    string addressString;  // we want to fill in this.
    string phoneString;    // we want to fill in this.
    

    // now search through the file till we find the line

    bool foundIt = false;

    while (!foundIt && !file.eof ())
    {
        string line;
        getline (file, line, '\n');
        if (storeString.compare (line) == 0)
             foundIt = true;
    }

    if (!foundIt)
    {
        cout << "I couldn't find the store.\n";
    }
    else
    {
        cout << "Found the store!\n";
        // now use getline to read the next two lines into addressString and phoneString.
        // you may want/need to parse phoneString to extract the separate phone numbers.
    }

    file.close ();
    return 0;
}

As a side note, some people here might not be crazy about my using eof () here. They think it should never be used. In this particular case, it's not a problem, and I didn't want to complicate the example any further than needed. Just keep in mind as you are going further that using eof () incorrectly can be dangerous. But it works here.

Edited 6 Years Ago by VernonDozier: n/a

Thank you again. I really appreciate ur help. I was trying to finish the codes but the itoa didn't work with me, so I used a string function and here is my code:

string str = "Stroe ";
	int i;
	string Store = str.insert(5,i);

What I want to do here is ask the user to input the store number and then I'll add this number to word Store and after that I'll search in the text file.

However, when I run this I got this error.
error: invalid conversion from 'int' to 'const char*'

Also, after I checked with my instructor, he told me that he might change the number of stores in the text file, so the I should make my codes accept any number of stores, so please any advise in how can I fix this error?

Edited 6 Years Ago by Mz3g: n/a

You can use a stringstream:

#include <sstream>
.....
stringstream ss;
cout <<"Enter store no.:";
cin >> number;
ss <<"Store "<<number;

Then use ss.str() to get the std::string version and ss.str().c_str() to get the c string version for strcmp.
There's probably a different approach that would work but I think this is the most intuitive (for your insert method to work you'd still need the integer as a string).

As far as the adaptability of your code to larger lists it should be fine. Try it out, add some more stores into the file. Add some "junk" in there to throw it off.
The code that VernonDozier gave you should be robust to these changing file size situations (he used the eof because it's fairly certain that your store number won't be the last or second to last line in a valid file). You could use getline to drive your while loop if you were concerned about running into the end of your file. So:

(if infile is your ifstream and chararray is an array of char,40 chars in length)
while(infile.getline(chararray,40)  //#40 so you can store the address ok
{
      if(strcmp( ...etc
}

Edited 6 Years Ago by jonsca: n/a

Thank you, but could you please explain more about this?

Then use ss.str() to get the std::string version and ss.str().c_str() to get the c string version for strcmp.

stringstream ss;
ss <<"Hello"; //send this into the stringstream
cout << ss;    //gives the address of ss
cout <<ss.str();  //gives "Hello"
string mystr = ss.str();
then mystr.c_str() is "Hello\0"

so with ss.str().c_str() we're first taking the stringstream object and using it's str() method to access the string, which we're then calling the c_str() method of that string to get the null terminated one.

Thank u Jonsca. It worked with me.
Now i'm trying to read the next two lines after Store 1 which contains the address and the numbers, however, I tried to use the same loop but It read all the data.

Store 1
Address: 1233 W 6th St.
Telephone/Fax: 6666666/5555555

Store 2
Address: 4444 E 29th St.
Telephone/Fax: 12121212/54545454

Here is my first codes:

while (!file.eof() )
		{
			string line;
			getline(file, line);
                        cout << line;

it read for me all the data after inputting the store number not one line at a time! so I tried using

char address;
int x1,x2;
fscanf (file, %c, address);
cout << "The address of Store" << i << " is: " << address << "\n";
fscanf(file, %d/%d, x1/ x2);
cout << "The phone number of Store "<< i << "is" << x1 << "\n";

Am I using fscan file in a wrong way? bcoz I got an error and I couldn't read the data!

Thank you again!

Stop using scanf() and fscanf() . They won't work for you because of your data, and you don't know how to use them -- which is a good thing, actually.

Please explain this loop:

while (!file.eof() )
{
	string line;
	getline(file, line);
        cout << line;

What does it do? What causes it to stop? How does it handle the Store # lines?

Thank you for your advice, this loop is to read the data in the next two lines after Store 1:
so simply it should read this two lines:
Address: 1233 W 6th St.
Telephone/Fax: 6666666/5555555

and output should be like this:
The address of store 1 is: 1233 W 6th St.
The telephone number of store 1 is: 6666666
The fax number of store 1 is: 5555555

However, that loop just read all the data I have in the text file and show it to the user.

I did not ask what if should do, I ask what it does do. In detail. Answer the questions I asked. There were 3 of them.

It doesn't do anything, I removed it from my codes because it didn't work well and I moved to fscanf because I thought it can read one line at a time.

Sorry, you were wrong. The other loop with getline() was the proper start. You just have to think about what you are trying to accomplish.

Write down on paper what you are trying to do. Step by step. Detail by detail. Read a line. What do you do with it?

that's what I couldn't figure it out! how can I read one line at a time and then send the number only on this line as output!
can u give me a hint.

Are you reading a 1) string or a 2) array of characters?
Did your instructor cover either of these?
Whichever one you are using, do you have any idea how to tell if the word Store is in it?
If your instructor and/or book covers them, now is the time to read the notes/book to understand them and the functions involved.

This question has already been answered. Start a new discussion instead.