-
looping through a char. seq. array of unknown length
I have the following basic code to retrieve a word from the user:
Code:
char word [20];
char question [] = "Please enter a word (less than 20 characters long)"
cout << question;
cin >> word;
I then want to loop through the array and check each char against something else but i am unsure of how to do this as the user could enter a any word of any length.
-
in general, this is C style and you should use c++ strings unless you have a reason not to.
However, they still work, so here goes:
the zero (0) char will be placed after the normal chars in the string to mark the end of string. The function strlen(char *) will return this for you, but you don't need it as you can just check for the zero yourself. There are a bunch of other char array routines, all are found in the <cstring> header or on a C compiler, <string.h>
-
You can used string data type and the at() function where this function will check for out bound.
I hope this help.
-
Best to read the user input into a string object instead of a fixed sized array:
std::string inp;
cout<"enter data: ";
cin>>str;
Then use str.size() to tell how many characters there are in the string and check each character with a loop.
Danny Kalev
-
ok. but how then do i loop through characters in a string?
-
Essentially I want to take two strings, compare them to see if they share any letters.
-
did you even read my post?
-
yh, but that just confused me more. I dont understand what you mean.
-
C strings end in zero automatically. If you treat char like an int, when it is == zero, you are done (you have read all the valid chars in your string).
-
ok but I have had to change to using strings now anyway.
Do you know how to loop through strings?
-
This should give you a clue:
for (int i=0; i<str.size(); i++)
{
cout<<str[i]<endl;
}
Danny Kalev
Similar Threads
-
By jamestmfbong in forum C++
Replies: 2
Last Post: 05-04-2009, 06:03 PM
-
By [gx]Shadow in forum Java
Replies: 5
Last Post: 10-25-2006, 10:20 PM
-
Replies: 9
Last Post: 07-28-2005, 08:40 PM
-
By Gastao Woelfert in forum VB Classic
Replies: 2
Last Post: 09-01-2000, 11:36 AM
-
By Gastao Woelfert in forum VB Classic
Replies: 0
Last Post: 09-01-2000, 08:59 AM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks