Search ids

I was wondering how I would be able to search through a file for a certain word and number.

Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>

using namespace std;

int main(){

	ifstream inputFile;

	char myString[50];
	int myString2[50];


	inputFile.open("itemname.txt");

	cout << "Reading string from file...\n";

	inputFile.getline(myString, 50, '\n');

	cout <<myString;


cin.ignore();
cin.get();
}


And here is my itemname.txt:

1
2
3
4
5
6
7
8
9
10
Tree - 1
Leaf - 2
Fire - 3
Water - 4
Earth - 5
Lightning - 6 
Lava - 7
Branch - 8
Brown - 9
White - 10
Prefer using std::string over arrays of char.
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.html

To read line by line from a text file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    constexpr const char* path = "itemname.txt" ;
    std::ifstream file(path) ;

    // read line by line from the input file
    std::string line ;
    while( std::getline( file, line ) )
    {
        // do whatever with line
        // ...
    }
}


To extract a word and a number from the line, use std::istringstream
http://www.cplusplus.com/reference/iostream/istringstream/istringstream/

for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
while( std::getline( file, line ) )
{
    std::istringstream stm(line) ; // #include <sstream>

    std::string word ;
    char seperator ;
    int number ;
    constexpr char EXPECTED_SEPERATOR = '-' ;

    if( ( stm >> word >> seperator >> number ) && ( seperator == EXPECTED_SEPERATOR ) )
    {
        // do whatever with word and number
    }
    else
    {
        // error in input: badly formed line
    }
}

Topic archived. No new replies allowed.