• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

C++ *Help*

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

joshhua5

Member
Joined
Jan 29, 2010
Hello,

I've just started to develop a game and first off i needed to make something to read the inputs and separate the Strings into 3 Different parts, Each

I've currently got the code I've been working on for a while, but I've hit a problem, Can one you your skilled eyes see it? I'm only new at this and I've probably taken the longest path possible.

Code:
int main ()
{
	// initilize Strings
	string C1;
	string C2;
	string C3;
	std::string Input;
	string Excract;
	int StringLength;
	// Get input
	getline(cin, Input, '\n');
	StringLength = Input.length();
	// Dessembel
	string Data[2][20];
	int Current(0);
	int CurrentC(0);
	for(Current; Current <= StringLength;Current++){
		Data[0][Current] = Input.substr(Current, Current);
		std::string ifstat = Input.substr(Current,Current);
		if(ifstat == " "){
			Data[CurrentC][Current] = "";
			CurrentC++;
		}
		Current++;
	};
	// Assembel
	int X(0);
	int Y(0);
	for(X; X <= 2; X++){
		for(Y; Y <= 20; Y++){
			int CurLetter(0);
			string k;
			k = Data[X][Y];
			Excract.insert(CurLetter, k);
			CurLetter++;
		}
		if(X = 0){C1 = Excract;};
		if(X = 1){C2 = Excract;};
		if(X = 2){C3 = Excract;};
		Excract = "";
	}
	// Check
	int t(0);
	cout << "\n" << "Comment 1:   "<< C1 << "\n";
	cout << "Comment 2:   "<< C2 << "\n";
	cout << "Comment 3:   "<< C3 << "\n";
	cout << "Input:   " << Input << "\n";
	cout << Excract << "\n";
	cout << "Array Check";
	for(int g(0); g <= 20; g++){
		for(int h(0); h <= 2; h++){
			cout << Data[g][h] << "\t";
		}
		cout << "\n";
	}
	cin >> t;

}
/*

Check string chariters 1 by one Pulling them out in order till it hits a Space,
once at a space Go to Next Command control and Continue without spaces.

String length
Use Extract going up by one number Each time 1,2  2,3  4,5 till it hits the string.length and stopping
if Excratction Hit's a space, Skip and Move Valuble.

String unbacked into a array then reassebled.
*/
 
I'm only new at this and I've probably taken the longest path possible.

  1. You're using string. Why aren't you using the appropriate methods? http://cplusplus.com/reference/string/string/
    • What the heck is substr(x,x)? Try at() and operator[].
    • Why are you manually parsing through every character to get to a space? Try find().
  2. You're either using namespaces or you're not. One type should not sometimes have a namespace and sometimes not.
This looks copy-pasted without any real knowledge of what it is doing. I suggest reading some books and language references before you try to write with it. Hello World is always a good start, then try some basic arrays with math operators (have two 4x4 matrices and add them together), then basic string input and output, then string manipulation.

http://www.freewebs.com/complib/tuts/C++Tut2.htm
http://augustcouncil.com/~tgibson/tutorial/arr.html
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.html
 
Last edited:
I quickly glanced over it and found one error... There might be more...

Code:
if(X = 0){C1 = Excract;};
if(X = 1){C2 = Excract;};
if(X = 2){C3 = Excract;};

Don't forget that comparison operator is ==, assignment operator is a single =. None of the above are expressions that should evaluate to bool. (Visual studio gives you an error if you do so, gcc might not be so restrictive and might evaluate every single one to true, not sure).

Here's what I would do: (works ok, just tested)

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
	// line = line to be parsed into smaller strings
	string line;
	getline(cin,line,'\n');

	// var = array of strings, each will hold a single word
	string var[3];
	// lastFound = last space found
	size_t lastFound = 0;
	/*
		We use substr string function to form a substring
		from lastFound (the last occurance of a space)
		all the way to the next space. We then have to increment
		lastFound to the newly found space.
	*/
	for(int i=0; i<3; i++)
	{
		var[i] = line.substr(lastFound,line.find(32,lastFound)-lastFound);
		lastFound = line.find(32,lastFound)+1;
	}

	cout << endl << "Output: " << endl;

	cout << "var[0] is : " << var[0] << endl;
	cout << "var[1] is : " << var[1] << endl;
	cout << "var[2] is : " << var[2] << endl;

	cin >> var[0];

	return 0;
}
 
  1. You're using string. Why aren't you using the appropriate methods? http://cplusplus.com/reference/string/string/
    • What the heck is substr(x,x)? Try at() and operator[].
    • Why are you manually parsing through every character to get to a space? Try find().
  2. You're either using namespaces or you're not. One type should not sometimes have a namespace and sometimes not.
This looks copy-pasted without any real knowledge of what it is doing. I suggest reading some books and language references before you try to write with it.

Agree with most of the above, however, there's nothing wrong with parsing through every single character to find a space, as long as you do it right. It makes things harder, but that's probably what find() does in the first place.
 
Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
	// line = line to be parsed into smaller strings
	string line;
	getline(cin,line,'\n');

	// var = array of strings, each will hold a single word
	string var[3];
	// lastFound = last space found
	size_t lastFound = 0;
	/*
		We use substr string function to form a substring
		from lastFound (the last occurance of a space)
		all the way to the next space. We then have to increment
		lastFound to the newly found space.
	*/
	for(int i=0; i<3; i++)
	{
		var[i] = line.substr(lastFound,line.find(32,lastFound)-lastFound);
		lastFound = line.find(32,lastFound)+1;
	}

	cout << endl << "Output: " << endl;

	cout << "var[0] is : " << var[0] << endl;
	cout << "var[1] is : " << var[1] << endl;
	cout << "var[2] is : " << var[2] << endl;

	cin >> var[0];

	return 0;
}

I read it and i don't really know what's going on with your code there (Works perfectly), could you care to explain what's happening?

  1. You're using string. Why aren't you using the appropriate methods? http://cplusplus.com/reference/string/string/
    • What the heck is substr(x,x)? Try at() and operator[].
    • Why are you manually parsing through every character to get to a space? Try find().
  2. You're either using namespaces or you're not. One type should not sometimes have a namespace and sometimes not.
This looks copy-pasted without any real knowledge of what it is doing. I suggest reading some books and language references before you try to write with it. Hello World is always a good start, then try some basic arrays with math operators (have two 4x4 matrices and add them together), then basic string input and output, then string manipulation.

http://www.freewebs.com/complib/tuts/C++Tut2.htm
http://augustcouncil.com/~tgibson/tutorial/arr.html
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.html

I didn't just copy it from a website, I sat there for 2 hours Writing that useless peice of code :D, My skills as i said are ****
and I'm still just learning.
1. I tried to get each character and put them in a spot in the array.
substr(x,x) was to get the Characters from the string one by one.
2. I have no idea.
 
Sure, I can explain it. I wrote more notes in the code below.

I'm a student myself... But I took a few C++ classes already, so I've got a hang of it. I don't have that much to do since it's a break for me, so I wrote quite a bit, hehe.

Ask away if you've got more questions. :)

Code:
#include <iostream>
#include <string>

// So we don't need to use the std:: prefix
using namespace std;

int main()
{
	/*
		First we declare a string called 'line' which will
		hold the entire line read. We then read to this string
		from standarnd input using the getline() function.
	*/
	string line;
	getline(cin,line,'\n');

	/* 
		Now we declare an array called var, which will hold
		three strings; each string will contain a single word.
	*/
	string var[3];

	/*	This is the loop part.

		First we declare a variable called lastFound. It is of 
		type size_t, which is usually the same as an unsigned int
		(a positive integer value). We need this variable to be
		of the type size_t because a function that we will use
		returns this (and takes it as one of the arguments also).

		What lastFound will represent is the character number of
		the last space. So, for example, let's say we have the
		following string (without the quotes):

		"Hello World! This is Fun!"

		At first, lastFound is initialized to 0.
		This means that the letter 'H' will be our starting point.
		From this letter we look for the next space, which is just
		after the 'o'. This space becomes our next lastFound, and its
		number is 6 (space is the sixth letter in the string).

		Then length from lastFound (0) to that space (6) (exclusive) gives us the word.

		We then begin this same process again, but this time we begin
		searching from lastFound+1, a 'W', which is the seventh letter
		in the string. And so we look for the next space again from the
		'W', which is right past the first exclamation point. 

		The length from lastFound (7) to that space (13) (exclusive) gives us the word.

		So now to explain the functions...

		var[i] = line.substr(lastFound,line.find(32,lastFound)-lastFound);

		substr() - this method returns a string from a certain point
		(lastFound) to another (next space that is found). We assign the
		return value to each one of the arrays elements.
		So the basic format is this:
		newString = myString.substr(begin,end);

		find() - this method finds the position in the string of
		a given character. It returns a variable of type size_t.
		So the basic format is this:
		whereIsSpace = myString.find(32,0);
		The first argument, 32, is an ascii value for space, what we want to find.
		The second argument, 0, is the position from which we begin the search.

		line.find(32,lastFound) finds the position of a space from lastFound.
		If we subtract lastFound from this, we get the length of the word.
		This result becomes our length for the substr method.

		Last but not least, we have to increment lastFound to the next space.
		line.find(32,lastFound) is the position of the space from lastFound.
		If we add one to this result, we get the next letter after lastFound.

		And the loop begins again, for the next word.

	*/
	size_t lastFound = 0;
	for(int i=0; i<3; i++)
	{
		var[i] = line.substr(lastFound,line.find(32,lastFound)-lastFound);
		lastFound = line.find(32,lastFound)+1;
	}

	cout << endl << "Output: " << endl;

	cout << "var[0] is : " << var[0] << endl;
	cout << "var[1] is : " << var[1] << endl;
	cout << "var[2] is : " << var[2] << endl;

	cin >> var[0];

	return 0;
}
 
Last edited:
Okay, i understand it Apart from
var = line.substr(lastFound,line.find(32,lastFound)-lastFound);

Why are we taking Lastfound at the end?

Thanks :D
 
Let's say we have the following string, without the quotes:

"Hello World"

Let's also assume that this is the first loop iteration, so that lastFound is 0.

line.find(32,lastFound) will find the position of the next space after lastFound, which is the space after the letter 'o'.

What we want, however, is to get the length of the word (in the substr() method, the second argument should be the length).

If we were to subtract the position of the old space (0) from the position of the new space (6), we get the length of the word. (exclusive, that is, [0,6) ). 0 to 5 is the length of the word.

So the "line.find(32,lastFound)-lastFound" gives us the length of the word.
"line.find(32,lastFound)" is the position of the new space (6).
"lastFound" is the position of the first character after the 'old' space (0).

Hope that makes sense.

I think I should have named lastFound to firstChar or something... It's confusing.
 
I managed to do it, but it's to Store some data which can be broken back down with the help i received above AND will allow for a save function.
 
I know you managed to do it, but there is a function called itoa() in <stdlib.h>, which stands for integer to ascii.

This would probably be the easiest way to do it.

Code:
#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

int main()
{
	char buffer[10];
	string word;
	int number = 84;

	// The arguments are: number to be converted, buffer for output, base (i.e. hex, octal, base 10)
	word = itoa(number,buffer,10);
	// itoa returns a pointer to the c string, which we can assign to our string
	// but we can't use it as a buffer, we have to use a cstring (buffer)
	cout << "Word is: " << word << endl;
	cout << "Word is: " << buffer << endl;

	cin >> word;
	return 0;
}
 
Thanks,

stringstream ss;
ss << number;
return ss.str();

Does the trick.
 
And scanning a string and replacing all capitals with a lowercase version...

though i plan to do this one myself :p try and make a function to do it.
 
And scanning a string and replacing all capitals with a lowercase version...

though i plan to do this one myself :p try and make a function to do it.

Check each character. If it is between 65 and 90 (inclusive), add 32. Or, use Boost's string (http://www.boost.org/doc/libs/1_45_0/doc/html/string_algo/usage.html#id2570604).


Is there a way to store both String and number in a singe array?

No. You could store every as a string, by converting numbers to strings, and enclosing them with some indicator ("NUM575236NUM") so you know to convert them back to numbers when reading.
 
Well, i created my capital thing and i seem to be getting a Error with Memory

"Unhandled exception at 0x7574b727 in Adventures of Vector.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0035eb10.."

Code:
string replaceCapitals(string Input)
{
	int hexLetter [26][2] = 
	{
	//  Upper  Lower
		{0x41, 0x61}, //A
		{0x42, 0x62}, //B
		{0x43, 0x63}, //C
		{0x44, 0x64}, //D
		{0x45, 0x65}, //E
		{0x46, 0x66}, //F
		{0x47, 0x67}, //G
		{0x48, 0x68}, //H
		{0x49, 0x69}, //I
		{0x4A, 0x6A}, //J
		{0x4B, 0x6B}, //K
		{0x4C, 0x6C}, //L
		{0x4D, 0x6D}, //M
		{0x4E, 0x6E}, //N
		{0x4F, 0x6F}, //O
		{0x50, 0x70}, //P
		{0x51, 0x71}, //Q
		{0x52, 0x72}, //R
		{0x53, 0x73}, //S
		{0x54, 0x74}, //T
		{0x55, 0x75}, //U
		{0x56, 0x76}, //V
		{0x57, 0x77}, //W
		{0x58, 0x78}, //X
		{0x59, 0x79}, //Y
		{0x5A, 0x7A}  //Z
	};
	for(size_t curChar(0); curChar <= Input.size(); curChar++)
		for(int i(0); i <= 26; i++)
			if(Input.find(hexLetter[i][1], curChar))
			{
				Input.erase(curChar, 0);
				Input.insert(curChar, hexLetter[i][2], (curChar - 1));
			}
	return Input;
}
 
That's entirely too much code for a simple manipulation. It's also horribly inefficient, because you're comparing each character in the string against 26 values, when you only need two.

For a string of 20 characters, your loop is 520 iterations, when it only needs to be 20.

Code:
std::string toLower(std::string str)
{
        for (int i = 0; i < str.size(); i++)
                if (static_cast<int>(str.at(i)) <= 90 && static_cast<int>(str.at(i)) >= 65)
                        str.replace(i, 1, 1, static_cast<char>(static_cast<int>(str.at(i)) + 32));
        return str;
}
 
Last edited:
Back