|
-
Jul 14th, 2003, 08:41 PM
#1
Thread Starter
Lively Member
Code: Getting char array's last character
This code will seek the ubound of a char array. Not really the ubound, just the last inputted character. Kind of like a Len() function.
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
char name[65536];
long ubound;
ubound = 0;
cout <<"Please enter your name: ";
cin >> name;
for (i=0; i<65536; i++)
{
if (name[i] == NULL){
if (ubound == 0){
ubound = i;
}
}
}
for (int x=0; x<ubound; x++)
{
cout << "Character " << x + 1 << " is " << name[x] << ". \n";
}
return 0;
}
www.hotvbforum.com for some great VB and C++ forums!
-
Jul 15th, 2003, 05:39 AM
#2
What's the point of your post?
Want the length of a string? Use strlen(const char *) from string.h (cstring in C++).
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Jul 15th, 2003, 01:49 PM
#3
But just for the sake of learning I have pointed out some bad things in your code:
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
// 65536 might be enough, but can you be sure?
// Why not use a std::string?
char name[65536];
long ubound;
ubound = 0;
cout <<"Please enter your name: ";
cin >> name;
// Why specify a limit?
// The char array is guaranteed to be 0-terminated.
// (unless your standard library implementation is buggy)
for (i=0; i<65536; i++)
{
// NULL is a pointer value, not a character value.
// You want to compare to '\0'.
if (name[i] == NULL){
// You found what you want.
// Why not say
// break;
// and be done with the loop?
// Otherwise you run a high risk of an access violation.
if (ubound == 0){
ubound = i;
}
}
}
for (int x=0; x<ubound; x++)
{
cout << "Character " << x + 1 << " is " << name[x] << ". \n";
}
return 0;
}
If you ever need it, the usual way to loop through a C-style string is
Code:
void constCharByChar(const char *str)
{
for(const char *p = str; *p; ++p) {
// Do something here.
// *p is the current character.
// You cannot alter the string.
}
}
void charByChar(char *str)
{
for(char *p = str; *p; ++p) {
// Do something here.
// *p is the current character.
// You can alter the string.
}
}
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
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
|
Click Here to Expand Forum to Full Width
|