Hello, I am having trouble going about taking a text file with a bunch of entries, like A43 A32 B45 A35 B23 etc, and having the numbers with A infront stored in one vector and the numbers with B infront stored in another. Anyone have hints for me?
so far i only know to do this:

string filename, line;
vector<string> anums, bnums;

ifstream infile(filename);

while(getline(infile, line))
{
   // somehow search the line and place each number in one of the vectors
   // until the end of the line, then it starts on next line until end of file.
   // Am i going to be using line.find() to find A and B then copying the next
   // position until i reach a space, then using find again? 
}

infile.close();

Recommended Answers

All 3 Replies

Since you're using a string I would recommend consulting this reference to see the different methods available for working with it. You can access the first character in the string like you could an array. In your case this would be something like:

if(line[0] == 'A') {
	// Place the string in the appropriate vector
}

This is assuming that you're reading in the A13 B23 A93 B23 line by line. Is this correct or do you also need to separate the elements from within the string?

i need to separate the elements within the string. so if one line contains A13 B23 A93 B23 then after that line has been checked, one vector will contain 13, 93 and the other vector will contain 23, 23. Is there a way to do this without strings? I don't really have a method yet, i just assumed i needed strings.

i need to separate the elements within the string. so if one line contains A13 B23 A93 B23 then after that line has been checked, one vector will contain 13, 93 and the other vector will contain 23, 23. Is there a way to do this without strings? I don't really have a method yet, i just assumed i needed strings.

Since your data contains letters and numbers, you're probably going to need to use a character string of some sort (either a C-style char[] array or a C++ std::string ) at some point. I'd recommend std::string unless you have a REALLY good reason.

As dmanw100 said, you can check the first letter using the [] for std::string . You can also use std::string::substr to extract just the number:

std::string numberPart

if ( originalString.length() > 1 )
    numberPart = originalString.substr(1);   // Get a substring starting at element 1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.