x.find() does not return the proper values for x.find('J'), x.find('K'), and x.find('.'). Do you know what could be the issue? It could possibly be x.substr() which is causing the issue.

I want the variable q to be "q_J30_K5.txt".

#include <iostream>
using namespace std;

short ato( string number ){ return atoi( number.c_str() ); }

short N, J, K;

int main(){
	string x = "X_N1234_J30_K5.dat"; // user will input this
		string n = x.substr( x.find('N')+1, x.find('J')-2 ); N = ato(n);
		string j = x.substr( x.find('J')+1, x.find('K')-2 ); J = ato(j);
		string k = x.substr( x.find('K')+1, x.find('.')-1 ); K = ato(k);
	string q = "q_J"; q += j; q+= "_K"; q += k; q+= ".txt";

	cout<< "n is: " << n <<endl;
	cout<< "j is: " << j <<endl;
	cout<< "k is: " << k <<endl;
	cout<< "q is: " << q <<endl;
}

Recommended Answers

All 2 Replies

Do you know what could be the issue?

Yes, the issue is you not understanding how substr works. The second argument is a count, not an index.

Yes, the issue is you not understanding how substr works. The second argument is a count, not an index.

.find() returns a size_t, and .substring() intakes two size_t variables, so it seemed compatible.

Now I see that the second variable in .substring() is a LENGTH, not a position. So my revised code is as below and functions. Thank you Narue once again for pointing me in the right direction.

#include <iostream>
using namespace std;

short ato( string number ){ return atoi( number.c_str() ); }

short N, J, K;

int main(){
	string x = "X_N1234_J30_K5.dat"; // user will input this
		string n = x.substr( x.find('N')+1, x.find('J')-x.find('N')-2 ); //N = ato(n);
		string j = x.substr( x.find('J')+1, x.find('K')-x.find('J')-2 ); //J = ato(j);
		string k = x.substr( x.find('K')+1, x.find('.')-x.find('K')-1 ); //K = ato(k);
	string q = "q_J"; q += j; q+= "_K"; q += k; q+= ".txt";

	cout<< "n is: " << n <<endl;
	cout<< "j is: " << j <<endl;
	cout<< "k is: " << k <<endl;
	cout<< "q is: " << q <<endl;
}
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.