473,803 Members | 3,030 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ Syntax Killing Me - Using Char Array For Strings

Hello everyone. Heads up - c++ syntax is killing me. I do quite well
in creating a Java program with very few syntax errors, but I get them
all over the place in c++. The smallest little things get me, which
brings me to...

I'm trying to create a program that gets a string from standard input
and then manipulates it a little bit. It has to be a char array and
not use string from the library.

Here are my prototypes:

//Header file MidTerm.h

#ifndef MIDTERM_H
#define MIDTERM_H

class MidTerm {
public:
void myappend(char [] , char []);
void mytokenizer(cha r []);
void myreverse(char [] );
void getString();
private:
char originalString[80];
char reversedString[80];
};

#endif

First off, how do I get access to originalString in main()? I always
get an undeclared identifier error. Is this because I didn't
initialize it? The thing is, I'm supposed to take input from the user
for the file - I don't know how to initilize it if that is the case.
I also wasn't sure how large of an array to make in the declaration.
>From what I understand, you must make a size, but how do you know the
size when any given sentence can be typed in? I picked 80, a number
large enough for most sentences...

Here is my main...

#include <iostream>
using namespace std;

#include "MidTerm.h"

int main() {

MidTerm test1;
test1.getString ();
//test1.mytokeniz er("I coundnt pass original string");
test1.myreverse (originalString );
return 0;
}

It's very simple so far, yet doesn't work. myreverse works if I
actually type in a string rather than use a variable as the
parameter. It reverses all the letters. However, I need to pass the
char array - not static text.

I'm just having a lot of syntax trouble with this char array as
string. How do I initialize it when the string will be input by
user? How do I pass it as a variable to a function correctly? How do
I know the size to use when declaring the char array? How can I get
it to work in the main()?

Any help would greatly be appreciated. I bombed this midterm because
it all dealt with char array, and I'm so used to using String in Java
- much simpler.

Here is that function...

void MidTerm::myreve rse(char os[]) {

int i = 0;
int j = strlen(os) -1;

while (i <= strlen(os)) {
reversedString[i] = os[j];
i++;
j--;
}

i = 0;
while (reversedString[i] != '\0') {
cout << reversedString[i];
i++;
}
}

Mar 9 '07
13 6254
Superman859 wrote:
>I agree - I would much rather be using strings than char arrays.
Unfortunately, the Professor specifically said we must use char
arrays. This is why I ask about it.
Some professors think you must learn C style programming to then learn C++.
Often that's how they did it. Just remember that high-level C++ can look
like it's very far from the metal, and that's where you should do most of
your work. And treat such professors as just coaches making you do mental
push-ups.
As for reversing the original string - here is the problem.
Forget this originalString thing and learn std::string. Get more C++
tutorials than just your class's textbook, too!

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Mar 9 '07 #11
Su*********@gma il.com wrote:
Hello everyone. Heads up - c++ syntax is killing me. I do quite well
in creating a Java program with very few syntax errors, but I get them
all over the place in c++. The smallest little things get me, which
brings me to...

I'm trying to create a program that gets a string from standard input
and then manipulates it a little bit. It has to be a char array and
not use string from the library.

Here are my prototypes:

//Header file MidTerm.h

#ifndef MIDTERM_H
#define MIDTERM_H

class MidTerm {
public:
void myappend(char [] , char []);
void mytokenizer(cha r []);
void myreverse(char [] );
void getString();
char[] is wrong. It's not illegal but it's confusing (put there for
newbies I think, this was a mistake). In C++ you cannot pass arrays as
parameter, so don't pretend you can, especially if you are use to
programming Java.

In C++ it's pointers

void myappend(const char*);
void mytokenizer(cha r*);
void myreverse(char* );
void getString();
private:
char originalString[80];
char reversedString[80];
Remove reversedString.

Allthough you know Java, you seem to think basic OO design doesn't apply
to C++? The method you've written above operate on originalString, you
don't need to pass originalString as a parameter. This is your biggest
mistake I think, not arrays and pointers.
};

#endif

First off, how do I get access to originalString in main()? I always
get an undeclared identifier error. Is this because I didn't
initialize it?
No. Access and initialisation are unrelated topic (true for Java as well).

In your class add

const char* getString() const { return originalString; }

The thing is, I'm supposed to take input from the user
for the file - I don't know how to initilize it if that is the case.
In your class add

void setString(const char* s) { strcpy(original String, s); }

Of course this code illustrates why you should be using std::string
instead if C strings, and why your professor is wrong.

There is no guarantee that the passed in string is not longer than the
room available in originalString. It's because of code like this that we
have to update our copies of Windows (TM) every month.

I also wasn't sure how large of an array to make in the declaration.
>>From what I understand, you must make a size, but how do you know the
size when any given sentence can be typed in? I picked 80, a number
large enough for most sentences...
Exactly, to code this properly, you have to use a pointer, and
dynamically resize the array to copy with the size of the sentence. If
you do that then you end up with something that looks very much like
std::string!

You really need to clarify with your professor whether you need t do
this or whether you can just pick a maximum length like 80.
john
Mar 9 '07 #12
Thanks for these last few responses - they've been pretty helpful.

You all are right. I think I'm forgetting the big picture of OOP
because I am getting so tied up with the language of C++. I forget
things like the public functions have access to private variables. I
just realized today that you cannot pass an array as a parameter or
return one. We just briefly started discussing pointers in class. I
feel the major problem with this professor is we don't do any 'live'
or real work. We've not once touched the computer as part of the
course during class. He talks about theory, what goes on with memory,
etc. but it's our first c++ class - we need more hands on type stuff
than that. This causes me to get caught up on syntax and details of c+
+, forgetting everything else I know.

Hopefully soon we will be allowed to use std::string.

Until then, I think I'm going to take learning the language into my
own hands - I feel like I'm not learning anything as part of the
course (I struggle with a simple program like this, yet I've made 100s
on all Homework assignments so far - that shouldn't happen). I'm
going to study it in more detail on my own.

Mar 9 '07 #13
"John Harrison" <jo************ *@hotmail.comwr ote in message
news:Ro******** ***********@new sfe2-win.ntli.net...
Su*********@gma il.com wrote:
Hello everyone. Heads up - c++ syntax is killing me. I do quite well
in creating a Java program with very few syntax errors, but I get them
all over the place in c++. The smallest little things get me, which
brings me to...

I'm trying to create a program that gets a string from standard input
and then manipulates it a little bit. It has to be a char array and
not use string from the library.

Here are my prototypes:

//Header file MidTerm.h

#ifndef MIDTERM_H
#define MIDTERM_H

class MidTerm {
public:
void myappend(char [] , char []);
void mytokenizer(cha r []);
void myreverse(char [] );
void getString();

char[] is wrong. It's not illegal but it's confusing (put there for
newbies I think, this was a mistake). In C++ you cannot pass arrays as
It was, IIRC, designed to make it clear that the parameter points to
multiple items (so expect a size parameter also somewhere) as opposed to a
single item. Doesn''t seem to be used that way very often anymore though,
and can cause confusion.

http://cm.bell-labs.com/cm/cs/who/dmr/chist.html
The notation survived in part for the sake of compatibility, in part under
the rationalization that it would allow programmers to communicate to their
readers an intent to pass f a pointer generated from an array, rather than a
reference to a single integer. Unfortunately, it serves as much to confuse
the learner as to alert the reader.
parameter, so don't pretend you can, especially if you are use to
programming Java.
<snip of useful information>

Dennis
Mar 10 '07 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3719
by: muser | last post by:
I'am having problem with the following: rec1len = strlen(temp1); temp1 is a character array, multi dimensional array. it has been initialised as char temp1; int rec1len. error for this message: C:\Program Files\Microsoft Visual Studio\MyProjects\Valid\Zenith124\Zenith.cpp(162) : error C2664: 'strlen' : cannot convert parameter 1 from 'char ' to 'const
5
7535
by: cppaddict | last post by:
Is it possible to avoid using push_back repeatedly when initializing a vector? That is, is there a vector syntax that would be analogous to the following array initialization syntax: MyClass myArray = { MyClass("Stan"), MyClass("Julie") }; Thanks for any ideas,
28
2711
by: Merrill & Michele | last post by:
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(void){ char *p; p=malloc(4); strcpy(p, "tja"); printf("%s\n", p); free(p); return 0;
11
3613
by: Sontu | last post by:
Consider the following code: int main(void) { char buffer; func(buffer); } void func(char *bufpas) {
3
42427
by: huey_jiang | last post by:
Hi All, I am trying to figure out a right syntax to convert an integer array into hex array. sprintf worked for me on doing single integer: int i, Iarray, n=15; char buf; sprintf(buf, "0x%02x", n); The above code worked. Howeve, what I am trying to do is to convert an
12
5536
by: arkobose | last post by:
my earlier post titled: "How to input strings of any lengths into arrays of type: char *array ?" seems to have created a confusion. therefore i paraphrase my problem below. consider the following program: #include<stdio.h> #define SIZE 1 int main()
7
2958
by: fakeprogress | last post by:
For a homework assignment in my Data Structures/C++ class, I have to create the interface and implementation for a class called Book, create objects within the class, and process transactions that manipulate (and report on) members of the class. Interface consists of: - 5 private variables char author; char title; char code;
2
2518
by: JJA | last post by:
I'm looking at some code I do not understand: var icons = new Array(); icons = new GIcon(); icons.image = "somefilename.png"; I read this as an array of icons is being built. An element of the array is an object itself but what is this syntax of the consecutive double quotes inside the brackets ?
13
2240
by: arnuld | last post by:
this does not work, i know there is some problem in the "for loop" of "print_arr" function. i am not able to correct the weired results i am getting. i have no compile time error, it is only semantic-bug that is causing the trouble: EXPECTED: january, february, march....december GOT: january, january, january.........january ------------- PROGRAMME -------------- /* Stroustrup, 5.9, exercise 10
0
9564
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10546
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10292
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10068
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7603
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6841
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.