Overclock.net - Overclocking.net
     
 
Home Gallery Reviews Blogs Register Today's Posts Mark Forums Read Members List


Go Back   Overclock.net - Overclocking.net > Software, Programming and Coding > Coding and Programming > Application Programming

Reply
 
LinkBack Thread Tools
Old 06-29-05   #1 (permalink)
PC Gamer
 
kris_cs1's Avatar
 
amd ati

Join Date: Apr 2005
Location: Chester, Cheshire
Posts: 218

Rep: 27 kris_cs1 is acknowledged by some
Unique Rep: 24
FAQs Submitted: 1
Trader Rating: 0
Default Lots of C++ Q's

Hi, rather than post on a C++ forum I thought I would post it here because I can't find any friendly + active C++ forums anywhere... Plus, i will post All of these questions in one post to save making new topics. Any help would be appreciated becuase i can find these things on google. Obviously they much be somewhere but still..

1) If you have a string, how do you take out just one of the words and put it into a variable?

2) How do you make a whole string upper or lowercase?

3) How can you 'chop' a certain number of characters off the end, beginning or middle of a string?

4) Why doesn't this work? i want it to store each line in the text file in a the array Line[]. E.g. Line 1 in Line[0] e.t.c However I can't get the array to work.

Code:

#include<fstream>
#include<iostream>
usingnamespace std;
 
int main(int argc, char* argv[])
{
ifstream infile; 
 
char s[80];
infile.open("test.txt");
 
if (infile.fail()) 
{
return 1;
exit(1);
}
 
char *Line[80];
int i = 0;
 
while (!infile.eof())
{
infile.getline(s, 80);
Line[i] = s;
cout << endl << s;
i++;
};
 
for (Index = 0; Index < i; Index++)
{
cout << endl << Line[Index];
};
 
infile.close();
return 0;
};

5) This code catches a runtime error but not the error if the user types in a non number in the operand variable. If however you remove the catch for the runtime error, it does catch the error if a user types in a non number in the operand variable. What is the reason for it not catching both errors? This is not the full code but if you want me to post it I will.

Code:
do
{
try
{
char Operator = GetOperator();
float Operand = GetOperand();
cout << Accumulate(Operator,Operand) << endl;
}
catch (runtime_error RuntimeError)
{
CALCErrorHandling::HandleRuntimeError(RuntimeError);
}
catch (...)
{
CALCErrorHandling::HandleNotANumberError();
};
} 
while (CALCPrompt::UserWantsToContinueYOrN("Use Calculator? "));
Errrrrmm well thats about if for now. If you need any more info just ask. Sorry if I'm asking too much but i know you guys are nice

Thanks very much
__________________
Kris



System: My System
CPU
AMD Sempron 2800+
Motherboard
ASUS A7N8X-VM
Sound Card
5.1 SURROUND SOUND
Power Supply
350W
Case
Black
OS
Windows XP Home SP2
Monitor
19"
kris_cs1 is offline   Reply With Quote
Old 06-29-05   #2 (permalink)
Programmer
 
MrSmiley's Avatar
 
amd nvidia

Join Date: Oct 2004
Location: Manhattan, Kansas
Posts: 1,060

Rep: 72 MrSmiley is acknowledged by some
Unique Rep: 57
FAQs Submitted: 1
Folding Team Rank: 817
Hardware Reviews: 1
Trader Rating: 0
Default

Quote:
Originally Posted by kris_cs1

1) If you have a string, how do you take out just one of the words and put it into a variable?
such as using string.h not a char array ( though either will work )?
Code:
 char blue[80];
 int OneWordCounter;//Nevr use variables like these! Keep Var's ~10 char.
 for(int i=0; i<=80; i++)
 {
 	 if(blue[i] == 'NULL'){
 	 {
 		   OneWordCounter++;
 		   if(OneWordCounter<=0)
 		   {		   
 				 for(int n=i; blue[n]!='NULL'; n++)
 				 blue[i]='';
 			}
 	  }
 			cout << blue[i];
 }//this will erase all but the first word.
Quote:
Originally Posted by kris_cs1
2) How do you make a whole string upper or lowercase?
Code:
 #include <ctype.h>
#include <iostream.h>
int main()
{
  char d='a';  
  d=toupper(d);
  cout<<d;
  return 0;
}
}
Quote:
Originally Posted by kris_cs1
3) How can you 'chop' a certain number of characters off the end, beginning or middle of a string?
review answer 1

Quote:
Originally Posted by kris_cs1
4) Why doesn't this work? i want it to store each line in the text file in a the array Line[]. E.g. Line 1 in Line[0] e.t.c However I can't get the array to work.

Code:

 #include<fstream>
 #include<iostream>
 usingnamespace std;
  
 int main(int argc, char* argv[])
 {
 ifstream infile; 
  
 char s[80];
 infile.open("test.txt");
  
 if (infile.fail()) 
 {
 return 1;
 exit(1);
 }
  
 char *Line[80];
 int i = 0;
  
 while (!infile.eof())
 {
 infile.getline(s, 80);
 Line[i] = s;
 cout << endl << s;
 i++;
 };
  
 for (Index = 0; Index < i; Index++)
 {
 cout << endl << Line[Index];
 };
  
 infile.close();
 return 0;
 };
 
First of all, I'd suggest allocating memory to *Line[x] or pulling it out of a pointer. Pointers, if not fully understood will be the death of you. Also, you never declare 'Index', another problem that pokes his head (this does matter what compiler you are on to see this problem or not) cout <<endl<<s; should throw an error. What you are doing is "clear the buffer->'\n'->print s" I'd say just use the escape code '\n'.

Quote:
Originally Posted by kris_cs1
5) This code catches a runtime error but not the error if the user types in a non number in the operand variable. If however you remove the catch for the runtime error, it does catch the error if a user types in a non number in the operand variable. What is the reason for it not catching both errors? This is not the full code but if you want me to post it I will.

Code:
 do
 {
 try
 {
 char Operator = GetOperator();
 float Operand = GetOperand();
 cout << Accumulate(Operator,Operand) << endl;
 }
 catch (runtime_error RuntimeError)
 {
 CALCErrorHandling::HandleRuntimeError(RuntimeError);
 }
 catch (...)
 {
 CALCErrorHandling::HandleNotANumberError();
 };
 } 
 while (CALCPrompt::UserWantsToContinueYOrN("Use Calculator? "));
 
Simple answer, Try/Catch works in visual Basics, it does not work well at all in C++ I would suggest not trying it.

Quote:
Originally Posted by kris_cs1
Errrrrmm well thats about if for now. If you need any more info just ask. Sorry if I'm asking too much but i know you guys are nice

Thanks very much
No Problem.
__________________
System: My System
CPU
Intel 2.8GHz
Motherboard
ESG smth
Power Supply
Antec TruePower 350Watt
OS
FreeBSD
MrSmiley is offline I fold for Overclock.net   Reply With Quote
Old 06-29-05   #3 (permalink)
<3 TB303
 
Xaimus's Avatar
 
amd nvidia

Join Date: Dec 2004
Location: Manhattan, KS
Posts: 575

Trader Rating: 0
Default

Quote:
Originally Posted by kris_cs1
1) If you have a string, how do you take out just one of the words and put it into a variable?
This is generally done via a tokenizer function; such a function would take a string and a delimiter as input, and return an array of seperate strings. However, that may be overkill if you only want to extract one word:

Code:
//inputs
//    string - char *, string to be searched
//    delimiter - the delimiter to look for
//    number - the word number you want extracted, zero indexed (ex getWord("what the boat", ' ', 1, 14) would return "the"
//    length - the length of the string array, includes zero termination--"what the boat" is 14 ("what the boat\0"), not 13
//returns
//    pointer to a new string that contains the desired word
//NOTE: this function allocates memory--be sure to delete the return variable when you're done
char * getWord(const char *string, char delimiter, int number, int maxlength) {
    char * word = new char[maxlength];  //create a new buffer, with length maxlength
    int wordPosition = 0;  //start off at word zero
    for (int i = 0; i < maxlength - 1; i++) {  //iterate through the string
        if (*(string + i) == delimiter) {  //is string[i] equal to the delimiter?
            if (++wordPosition == number) {  //yes.  increment wordPosition.  is wordPosition equal to number?
                int j = 0;  //yes, start off another counter
                i++;  //go to the position right after the delimiter
                while (*(string + i) != delimiter && i < maxlength - 1) {  //while string[i] is not equal to the delimiter and i remains less than the maximum length
                    *(word + j) = *(string + i);  //word[j] = string[i]
                    i++; j++;
                }
                *(word + j) = '\0';  //zero-terminate our new string
                return word;
            }
        }
    }
    return NULL;  //OH NOES SOMETHING DIDN'T GO TOO WELL
}
holy jesus this code is disgusting
i'm not even sure if it works
oh well.

I'm pretty sure that there's a standard POSIX C library function call to do something like this, but I'm not sure. Though, this should provide a general idea as to how you would do such a thing.

If you can, use STL strings (or QStrings, or NOT raw c-strings). They're much easier to use, and most string object implementations include methods to convert its contents into c-strings for use with legacy functions.

Anyhow, I need to return to "work"--I'll try my hand at the other questions later.
__________________
System: Turd
CPU
Sempron 2800+ :(
Motherboard
GA7NF-RZ :(
Memory
1.25GB
Graphics Card
geForce 6800XT
Hard Drive
80GB + 120GB
Sound Card
M-Audio Audiophile 192 :D
Power Supply
500W Seasonic S12
Case
Black Antec P180 :D
OS
FreeBSD 6.2-RELEASE :D :D
Monitor
Two 17" CRTs
Xaimus is offline Overclocked Account   Reply With Quote
Old 06-29-05   #4 (permalink)
PC Gamer
 
kris_cs1's Avatar
 
amd ati

Join Date: Apr 2005
Location: Chester, Cheshire
Posts: 218

Rep: 27 kris_cs1 is acknowledged by some
Unique Rep: 24
FAQs Submitted: 1
Trader Rating: 0
Default

Xaimus, thank you that is EXACTLY what I wanted for that one.

MrSmiley, the first one wasn't really what I meant, I meant for any word, not just the first word like the code Xaimus posted but thanks anyway for that.

Thank you MrSmiley for the second answer. However I still need a bit more help on it. The code you posted just seems to work for one letter. To make it work for a whole sting i have tried to make a function but can't seem to get it to work. I think the main problem is i can't add the capitalized letter to the new string. It also says "The variable 'newSentence' is being used without being defined." Here it is if anyone can help on that:

Code:

char* Upper(char *Sentence)
{
char *newSentence;
for (int i = 0; i < KrisIO::Len(Sentence); i++)
{
char *newSentence;
char Letter = Sentence[i];
Letter = toupper(Letter);
newSentence = newSentence + Letter;
}
return newSentence;
}
(that KrisIO::Len() function is my own to count the number of letters in a string)

For Number 3 if someone can fix the code above , I should be able to do that aswell.

Question 4 - yeah, i don't really understand pointers.... anyplace got a really EASY tutorial? Does anyone have any sample code of storing the lines from a text file into an array?

Question 5 - Hmmmm... why is that? That is just copied out of my C++ book you see and i don't know how else to catch errors yet

Well thanks so far guys!
Keep the help coming (please! )
__________________
Kris



System: My System
CPU
AMD Sempron 2800+
Motherboard
ASUS A7N8X-VM
Sound Card
5.1 SURROUND SOUND
Power Supply
350W
Case
Black
OS
Windows XP Home SP2
Monitor
19"

Last edited by kris_cs1 : 06-29-05 at 05:13 PM.
kris_cs1 is offline   Reply With Quote
Old 06-29-05   #5 (permalink)
Overclocker
 
Join Date: Dec 2004
Posts: 401

Rep: 65 Melraidin is acknowledged by some
Unique Rep: 48
FAQs Submitted: 4
Folding Team Rank: 264
Trader Rating: 1
Default

Quote:
Originally Posted by kris_cs1
Hi, rather than post on a C++ forum I thought I would post it here because I can't find any friendly + active C++ forums anywhere... Plus, i will post All of these questions in one post to save making new topics. Any help would be appreciated becuase i can find these things on google. Obviously they much be somewhere but still..

1) If you have a string, how do you take out just one of the words and put it into a variable?

2) How do you make a whole string upper or lowercase?

3) How can you 'chop' a certain number of characters off the end, beginning or middle of a string?

4) Why doesn't this work? i want it to store each line in the text file in a the array Line[]. E.g. Line 1 in Line[0] e.t.c However I can't get the array to work.

[snip]

5) This code catches a runtime error but not the error if the user types in a non number in the operand variable. If however you remove the catch for the runtime error, it does catch the error if a user types in a non number in the operand variable. What is the reason for it not catching both errors? This is not the full code but if you want me to post it I will.

[snip]

Errrrrmm well thats about if for now. If you need any more info just ask. Sorry if I'm asking too much but i know you guys are nice

Thanks very much

1) ANSI C++ string tokenizer: [url]http://www.cplusplus.com/ref/cstring/strtok.html

It basically takes your string as input with a delimiter, then returns a pointer to each token in sequence. It also replaces the delimiter in the original string with a null. Sample code at URL above.

2) For uppercase:

Code:
void ToUpper ( char *pzInput )
{
    while ( *pzInput != NULL )
         *pzInput &= 0xDF;
}
That will only work for alphabetic characters. I'll leave it up to you to determine how to change it to work with all characters.

That's all I've got time for at the moment, if you'd like other alternative answers I'll post later.
Melraidin is offline I fold for Overclock.net   Reply With Quote
Old 06-29-05   #6 (permalink)
Overclocker
 
Join Date: Dec 2004
Posts: 401

Rep: 65 Melraidin is acknowledged by some
Unique Rep: 48
FAQs Submitted: 4
Folding Team Rank: 264
Trader Rating: 1
Default

Quote:
Originally Posted by kris_cs1
Xaimus, thank you that is EXACTLY what I wanted for that one.

MrSmiley, the first one wasn't really what I meant, I meant for any word, not just the first word like the code Xaimus posted but thanks anyway for that.

Thank you MrSmiley for the second answer. However I still need a bit more help on it. The code you posted just seems to work for one letter. To make it work for a whole sting i have tried to make a function but can't seem to get it to work. I think the main problem is i can't add the capitalized letter to the new string. It also says "The variable 'newSentence' is being used without being defined." Here it is if anyone can help on that:

Code:

char* Upper(char *Sentence)
{
char *newSentence;
for (int i = 0; i < KrisIO::Len(Sentence); i++)
{
char *newSentence;
char Letter = Sentence[i];
Letter = toupper(Letter);
newSentence = newSentence + Letter;
}
return newSentence;
}
(that KrisIO::Len() function is my own to count the number of letters in a string)

For Number 3 if someone can fix the code above , I should be able to do that aswell.

Question 4 - yeah, i don't really understand pointers.... anyplace got a really EASY tutorial? Does anyone have any sample code of storing the lines from a text file into an array?

Question 5 - Hmmmm... why is that? That is just copied out of my C++ book you see and i don't know how else to catch errors yet

Well thanks so far guys!
Keep the help coming (please! )
3) You need to allocate some memory for the char pointer newSentence. Try malloc (). BTW, have you considered to using the STL's string class?
Melraidin is offline I fold for Overclock.net   Reply With Quote
Old 06-29-05   #7 (permalink)
Programmer
 
MrSmiley's Avatar
 
amd nvidia

Join Date: Oct 2004
Location: Manhattan, Kansas
Posts: 1,060

Rep: 72 MrSmiley is acknowledged by some
Unique Rep: 57
FAQs Submitted: 1
Folding Team Rank: 817
Hardware Reviews: 1
Trader Rating: 0
Default

Why would you want to use malloc/free and not new/delete? I mean "I guess they're the same thing" (not really...). New seems to be easier for people to catch on. Also, don't worry about not fully understanding pointers, that usually takes people a bit of time to understand. I do like cplusplus.com's version.
__________________
System: My System
CPU
Intel 2.8GHz
Motherboard
ESG smth
Power Supply
Antec TruePower 350Watt
OS
FreeBSD
MrSmiley is offline I fold for Overclock.net   Reply With Quote
Old 06-30-05   #8 (permalink)
PC Gamer
 
kris_cs1's Avatar
 
amd ati

Join Date: Apr 2005
Location: Chester, Cheshire
Posts: 218

Rep: 27 kris_cs1 is acknowledged by some
Unique Rep: 24
FAQs Submitted: 1
Trader Rating: 0
Default

Melraidin, thanks very much. However I cannot get the second one to work. It says something about a violation..
I would really love to get my own functions to work. I seem to have the same error as the Upper()0 finction with this one as well:

Code:
char* Mid(constchar *Sentence, int FromNumber, int ToNumber)
{
char *newSentence;
if (ToNumber == 0)
ToNumber = KrisIO::Len(Sentence);
for (int i = (FromNumber--); i <= ToNumber; i++)
{
char *newSentence;
newSentence += Sentence[i];
}
return newSentence;
}
If someone could possibly help me to get these to work I think I would learn a lot and I would be EXTREMELY grateful!

Well, i'm off to read up on pointers and allocating memory...
Thanks so far guys! You're great!
__________________
Kris



System: My System
CPU
AMD Sempron 2800+
Motherboard
ASUS A7N8X-VM
Sound Card
5.1 SURROUND SOUND
Power Supply
350W
Case
Black
OS
Windows XP Home SP2
Monitor
19"
kris_cs1 is offline   Reply With Quote
Old 06-30-05   #9 (permalink)
<3 TB303
 
Xaimus's Avatar
 
amd nvidia

Join Date: Dec 2004
Location: Manhattan, KS
Posts: 575

Trader Rating: 0
Default

Quote:
Originally Posted by kris_cs1
3) How can you 'chop' a certain number of characters off the end, beginning or middle of a string?
If you want to remove characters off the end of a string, a quick (and dirty!) method is to just slap a \0 in the spot right after the last character in the substring you want to preserve. It'd probably be a good idea to NULL out the rest of the string, but meh.
The solution that comes to my mind for removing characters from the beginning or middle of a string is something like:
Code:
void strCut(char *str, int beg, int length) {
    int max = beg + length, stlen = strlen(str);
    int i = max;
    for (; beg < max; beg++) {
        if (i < stlen) {
            *(str + beg) = *(str + i);
            i++;
        } else {
            *(str + beg) = '\0';
            return;
        }
    }
}
again, horrible code, probably has strange side-effects (it sure the hell doesn't zero out unused memory in the name of security), not sure if it works, work is boring, &c.
__________________
System: Turd
CPU
Sempron 2800+ :(
Motherboard
GA7NF-RZ :(
Memory
1.25GB
Graphics Card
geForce 6800XT
Hard Drive
80GB + 120GB
Sound Card
M-Audio Audiophile 192 :D
Power Supply
500W Seasonic S12
Case
Black Antec P180 :D
OS
FreeBSD 6.2-RELEASE :D :D
Monitor
Two 17" CRTs
Xaimus is offline Overclocked Account   Reply With Quote
Old 06-30-05   #10 (permalink)
Overclocker
 
Join Date: Dec 2004
Posts: 401

Rep: 65 Melraidin is acknowledged by some
Unique Rep: 48
FAQs Submitted: 4
Folding Team Rank: 264
Trader Rating: 1
Default

Quote:
Originally Posted by kris_cs1
Melraidin, thanks very much. However I cannot get the second one to work. It says something about a violation..
I would really love to get my own functions to work. I seem to have the same error as the Upper()0 finction with this one as well:

Code:
char* Mid(constchar *Sentence, int FromNumber, int ToNumber)
{
char *newSentence;
if (ToNumber == 0)
ToNumber = KrisIO::Len(Sentence);
for (int i = (FromNumber--); i <= ToNumber; i++)
{
char *newSentence;
newSentence += Sentence[i];
}
return newSentence;
}
If someone could possibly help me to get these to work I think I would learn a lot and I would be EXTREMELY grateful!

Well, i'm off to read up on pointers and allocating memory...
Thanks so far guys! You're great!
If I have time tonight I may be able to get back into some C++ coding and post some of my code cleaned up a bit, but at the moment a bit busy. Seeing C++ again is really reminding me why I like C# so much! ie: string.ToUpper ()
Melraidin is offline I fold for Overclock.net   Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools



All times are GMT -4. The time now is 03:00 AM.


Overclock.net is a Carbon Neutral Site Creative Commons License Internet Security By ControlScan

Terms of Service / Forum Rules | Privacy Policy | Advertising | Become an Official Vendor
Copyright © 2008 Shogun Interactive Development. Most rights reserved.
Page generated in 0.55231 seconds with 8 queries