Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Am I Doing This Right?

c++ string realloc ascii value

  • Please log in to reply
16 replies to this topic

#1 Hydrokr0n1k

Hydrokr0n1k

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 57 posts
  • Learning:C++, JavaScript

Posted 23 April 2012 - 01:23 PM

ok I have put these several functions in one .cpp and attempted to call the mall one after another am I doing it right?

#include <cmath>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
#include<stdio.h>
#include <string.h>
using namespace std;
int doubledelete();
int numberwordsinstring();
int reversewloop();
int main();
int reverse();
int asciistring();
// Part 1
//1. Find Number in Middle and return it
std::string middleCharacters(const std::string &str)
{
    if (str.length() <= 0) return ""; // For an empty string, return an empty string (customize this as desired)
    return str.substr((str.length() - 1) / 2, 2 - str.length() % 2);
}
//Part 2 Repeater

std::string repeat( const std::string &word, int times ) {
   std::string result ;
   result.reserve(times*word.length()); // avoid repeated reallocation
   for ( int a = 0 ; a < times ; a++ )
	  result += word ;
   return result ;
}

int main( ) {
   std::cout << repeat( "Ha" , 5 ) << std::endl ;
   return 0 ;
}
// Part 3
//   loop through the string looking for ".  "
//   when ".  " is found, delete one of the spaces
//   Repeat process until ".  " is not found. 
string forceSingleSpaces1 (string str) {
    size_t found(str.find(".  "));
    while (found !=string::npos){
	    str.erase(found+1,1);
	    found = str.find(".  ");
    }
    return str;
}
int doubledelete(){
    cout << forceSingleSpaces1("sentence1.  sentence2.  end.  ") << endl;
    return EXIT_SUCCESS;
}
// Part 4 number of words in string
int numberwordsinstring()
{
int i, numspaces;
char nextChar;
string msg;
numspaces=1;
cout << "Type in a string\n";
getline(cin, msg);
// checks each character in the string
for (i=0; i<int(msg.length()); i++)
{
  nextChar = msg.at(i); // gets a character
  if (isspace(msg[i]))
   numspaces++;
}
cout << "\nThere are " << numspaces << " words in this string.";
cin.ignore();
return 0;
}
// Part 6 Reverse
char STOP[265];
void reverse(char* a)// error: initializing argument 1 of ‘int reverse(char*)’ [-fpermissive]
{
int c = strlen(a) - 1;
for (; c >= 0; c--)
{
cout << a[c];
}
}
int reversewloop()
{
cout<<"Please digit an input to be reversed: "<<endl;
cin.getline(STOP,265);
reverse(STOP); //error: invalid conversion from ‘char’ to ‘char*’
// [-fpermissive]
system("pause");
return 0;
}
//7. Reverse no loops

int complexReverseString(string userInput)
{
string source(userInput);
string target( source.rbegin(), source.rend() );
cout << "The reversed string is " << target << endl;
return 0;
}
int reverse()
{
ifstream input;
string forward;
cout << "Please enter a string to see its reverse. (Will display reverse twice)" << endl;
input.open("information.txt");
cin >> forward;
//reverseString(forward, findStringSize(forward)); a function I'm not actually calling
input >> forward;
complexReverseString(forward);

input.close();
system ("pause");
}
//8 Ascii
//C program to accept a string from user and
//display its ascii value and
//then display sum of all ascii value of strings

int asciistring() {
char String[100];
int Sum,Index;
Sum=0; //Sum is initially zero
printf("Enter the string:\n");
gets(String); //Accept String from User
for(Index=0;Index<strlen(String);Index++)
{
Sum+=(String[Index]); //Adds (the ASCII values of) the String characters.
}
printf("The sum is %d\n",Sum); //Printing it as %d gives the equivalent ASCII value.
return 0;
}
//9 acsiiArraysum
//10 getput
I still have three more functions to put in there but am I going about this the right way?

guess my question should be am I declaring and calling my prototypes right if that is the right terminology
  • 0

#2 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 23 April 2012 - 04:03 PM

g++ -Wall gives me three warnings.

hk.cpp: In function ‘int numberwordsinstring()’:
hk.cpp:57:6: warning: variable ‘nextChar’ set but not used [-Wunused-but-set-variable]
hk.cpp: In function ‘int reverse()’:
hk.cpp:114:1: warning: no return statement in function returning non-void [-Wreturn-type]
hk.cpp: In function ‘int asciistring()’:
hk.cpp:126:32: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#3 Hydrokr0n1k

Hydrokr0n1k

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 57 posts
  • Learning:C++, JavaScript

Posted 23 April 2012 - 07:39 PM

gave me these lol total bummer what program is it that you are using G++ -wall ?
strings.cpp(152): warning C4996: 'gets': This function or variable may be unsafe. Consider using gets_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
e:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(277) : see declaration of 'gets'
strings.cpp(154): warning C4018: '<' : signed/unsigned mismatch
strings.cpp(138): error C4716: 'reverse' : must return a value

as well my errors dont appear when I run the individual funtions themselves and your errors appear to be that I am not calling them right so how would I call them appropietly?
  • 0

#4 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 23 April 2012 - 09:59 PM

My quick thought process:

strings.cpp(138): error C4716:'reverse': must return a value


It claims reverse must return a value.

I go up and view the definition
void reverse(char* a)// error: initializing argument 1 of ‘int reverse(char*)’ [-fpermissive]
{
int c = strlen(a) - 1;
for (; c >= 0; c--)
{
cout << a[c];
}
}

Curious, there is nothing to return, being a void.

I consider:
  • Is this function previously defined to return an int?
  • Is the declaration ("forward declaration") not matching to the definition?
I go up to the declarations:

int doubledelete();
int numberwordsinstring();
int reversewloop();
int main();
int reverse();
int asciistring();


And there, I spot what is declaring it as returning an int.

As for the other warnings..

One variable is unused (WingedPanther's first warning) and that is only a warning not an error. It should however be taken care of before you forget about it, or do not wish to use it.

signed/unsigned match comes from the fact that something somewhere is using unsigned integers. You are using signed (int), so the function called must be returning the unsigned integral data type.

Lets look at strlen: http://www.cplusplus...cstring/strlen/

It appears to return a size_t datatype, which may possibly be an unsigned integer on your compiler (and WP's). You will have to decide if comparing the two data types matters, or if you should turn Index in to an unsigned int.

With gets, it is wise to read up on what it does and its shortcomings on working with the buffer it writes to. Using gets_s is an OS-specific fix of which Microsoft provides, you can look in to fgets (treating stdin, without quotes, as the file name you will be reading from) to read in to a buffer, we have some good tutorials on this (see Guest's: http://forum.codecal...ing-files-in-c/)

Alexander.
  • 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#5 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 24 April 2012 - 03:41 PM

I use GNU gcc for my compiler. Different compilers give different error messages/warrnings and have different compiler options.
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#6 Hydrokr0n1k

Hydrokr0n1k

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 57 posts
  • Learning:C++, JavaScript

Posted 25 April 2012 - 09:45 PM

ok I appreciate the very nice neat short get tutorial it will actually help me on part 10 of this lol however the code itself when broken down into the individual functions works great its when they are together that it is crapping out on me lol should my declarations have semicolons afterwards like

#include  <iostream>
int asciistring(); <~~ should I remove it?

    int asciistring()
       code for int asciistring here .......
an as well am I declaring them approipately is that how I am supposed to do it?

  • Is the declaration ("forward declaration") not matching to the definition?
I go up to the declarations:



And there, I spot what is declaring it as returning an int.
Alexander.


so I dont understand Ia mdeclaring something I should not be and need to delte the in decleration so I need to remove it right the part at the top the "declarattion"

for the reverse loops this is what I originally had and its works fine but to intigrate it with the rest I had to change int main() to int reversewloop() but that is all i changed to why would it not be working when with the rest of the functions but works alone?
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
char STOP[265];
void reverse(char* a)// error: initializing argument 1 of ‘int reverse(char*)’ [-fpermissive]
{
int c = strlen(a) - 1;
for (; c >= 0; c--)
{
cout << a[c];
}
}
int main()
{
cout<<"Please digit an input to be reversed: "<<endl;
cin.getline(STOP,265);
reverse(STOP); //error: invalid conversion from ‘char’ to ‘char*’
// [-fpermissive]
system("pause");
return 0;
}

  • 0

#7 Hydrokr0n1k

Hydrokr0n1k

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 57 posts
  • Learning:C++, JavaScript

Posted 26 April 2012 - 09:37 PM

did a little toying with the ascii counter so when its

#include<stdio.h>
#include <string.h>
int main() {
it works great then when I change it to the below
#include<stdio.h>
#include <string.h>
int asciistring() {
it does not work so what am I supposed to change int main() to if there is more then int main in the program? am I supposed to declare the int ascii() a certain way to make it work? if so how?
when I find out how to do this properly I will be able to fix alot of my projects lol
  • 0

#8 Hydrokr0n1k

Hydrokr0n1k

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 57 posts
  • Learning:C++, JavaScript

Posted 26 April 2012 - 10:03 PM

ok think I got something to compile is it right I do not know I just know I did not get an error lol and my heart jumped lol but heres what i got and many thanks to alaxander and the link ok so here we go FYI pap.txt is the name of the file I want to read on my computer

#include <stdio.h>
#include <cstring>
#include <fstream>
#include <string>

#include <string.h>
using namespace std;

int main()
{
string strdata = "pap.txt";
fstream streamObject("pap.txt");
fstream localFile("pap.txt");
fstream newFile("new.txt");
	    FILE *filepointer;
	    int character;
	    filepointer=fopen("pap.txt", "r"); /* filepointer points to data.txt */
	    if (filepointer==NULL) { /* error opening file returns NULL */
			    printf("Could not open data.txt!\n"); /* error message */
			    return 1; /* exit with failure */
	    }
	    /* while character is not end of file */
	    while ((character=fgetc(filepointer)) != EOF) {
			    putchar(character); /* print the character */
	    }
	    fclose(filepointer); /* close the file */
	    return 0; /* success */
}

  • 0

#9 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 26 April 2012 - 10:19 PM

Regarding the forward declaration. You have declared it to return int (int function(...))

Yet, you had defined it to return nothing:

void function() { ...

If you want to use function() in main() (which is at top, way before function() is defined) then the compiler must know what it returns and what its parameters will be.

If the signature (declaration) of function() is different from the definition, then your compiler will tell you there is an error in that. Why? If the compiler sets up the assembly to hold an int (which the declaration says), yet when the code is compiled and the function is linked to your program it doesn't return an int, you are wasting memory. If it is the other way around, you could be doing something bad. This is why it halts.

You can define function() in another file, all you need is the correct declaration for it to be used. You do not need to remove it or define all the functions before main() to "fix" this.

This is a topic you should get a solid understanding in before you move on,

Alexander.
  • 1

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#10 Hydrokr0n1k

Hydrokr0n1k

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 57 posts
  • Learning:C++, JavaScript

Posted 27 April 2012 - 03:53 PM

so then it would be

#include <cmath>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
#include<stdio.h> 
#include <string.h> 

using namespace std;

int main()
{
int doubledelete();
int repeat();
int numberwordsinstring();
int reverseloop;
int reversenoloop();
int asciistring();
int acsiiArraysum();
int getput();
}
//***************************************************************
// Part 1
//1. Find Number in Middle and return it
std::string middleCharacters(const std::string &str)
{
if (str.length() <= 0) return ""; // For an empty string, return an empty string (customize this as desired)
return str.substr((str.length() - 1) / 2, 2 - str.length() % 2);
}
//***************************************************************
//Part 2 Repeater

std::string repeat( const std::string &word, int times ) {
std::string result ;
result.reserve(times*word.length()); // avoid repeated reallocation
for ( int a = 0 ; a < times ; a++ ) 
result += word ;
return result ;
}

int repeat() {
std::cout << repeat( "Ha" , 5 ) << std::endl ;
return 0 ;
}
//***************************************************************
// Part 3
//   loop through the string looking for ".  "
//   when ".  " is found, delete one of the spaces
//   Repeat process until ".  " is not found.  

string forceSingleSpaces1 (string str) {
size_t found(str.find(".  "));
while (found !=string::npos){
str.erase(found+1,1);
found = str.find(".  ");
    }

return str;
}

int doubledelete()
{
cout << forceSingleSpaces1("sentence1.  sentence2.  end.  ") << endl;
return EXIT_SUCCESS;
}
//***************************************************************
// Part 4 number of words in string

int numberwordsinstring()
{
int i, numspaces;
char nextChar;
string msg;

numspaces=1;

cout << "Type in a string\n";
getline(cin, msg);

// checks each character in the string
for (i=0; i<int(msg.length()); i++)
{
nextChar = msg.at(i); // gets a character
if (isspace(msg[i]))
numspaces++;
}
cout << "\nThere are " << numspaces << " words in this string.";
cin.ignore();
return 0;
}
//***************************************************************
// Part 6 Reverse

char STOP[265];

void reverse(char* a)// error: initializing argument 1 of ‘int reverse(char*)’ [-fpermissive]

{
int c = strlen(a) - 1;
for (; c >= 0; c--)
{
cout << a[c];
}
}
int reverseloop()
{

cout<<"Please digit an input to be reversed: "<<endl;
cin.getline(STOP,265);

reverse(STOP); //error: invalid conversion from ‘char’ to ‘char*’
// [-fpermissive]

system("pause");
return 0;
}
//***************************************************************
//7. Reverse no loops


int complexReverseString(string userInput)
{
string source(userInput);
string target( source.rbegin(), source.rend() );
cout << "The reversed string is " << target << endl;

return 0;
}
int reversenoloop()
{
ifstream input;
string forward;

cout << "Please enter a string to see its reverse. (Will display reverse twice)" << endl;
input.open("information.txt");
cin >> forward;
//reverseString(forward, findStringSize(forward)); a function I'm not actually calling
input >> forward;
complexReverseString(forward);

input.close();

system ("pause");

}
//***************************************************************
//8 Ascii
//C program to accept a string from user and 
//display its ascii value and 
//then display sum of all ascii value of strings 


int asciistring() { 

char String[100]; 
int Sum,Index; 
Sum=0; //Sum is initially zero 

printf("Enter the string:\n"); 
gets(String); //Accept String from User 

for(Index=0;Index<strlen(String);Index++) 
{ 
Sum+=(String[Index]); //Adds (the ASCII values of) the String characters. 
} 

printf("The sum is %d\n",Sum); //Printing it as %d gives the equivalent ASCII value. 

return 0; 

}
//***************************************************************
//9 acsiiArraysum
using std::cout; 
using std::endl; 

int acsiiArraysum() 
{ 
const int myArrayNumberOfElements(5); 
double myArray[myArrayNumberOfElements] = {1.1, 4.5, 5.7, 7.9, 10}; 
double sum(0); 
for (int i(0); i < myArrayNumberOfElements; i++) 
{ 
sum +=myArray[i]; 
} 

cout << endl << "Sum of all elements: " << sum << endl; 

system("PAUSE"); 
return 0; 
}
//***************************************************************
//10 getput

int getput()
{
string strdata = "pap.txt";
fstream streamObject("pap.txt");
fstream localFile("pap.txt");
fstream newFile("new.txt");
FILE *filepointer;
int character;
filepointer=fopen("pap.txt", "r"); /* filepointer points to data.txt */
if (filepointer==NULL) { /* error opening file returns NULL */
                printf("Could not open data.txt!\n"); /* error message */
                return 1; /* exit with failure */
    }
        /* while character is not end of file */
while ((character=fgetc(filepointer)) != EOF) {
                putchar(character); /* print the character */
    }
        fclose(filepointer); /* close the file */
return 0; /* success */
}
this is my output result now with all my functions in there lol
1>------ Build started: Project: string, Configuration: Debug Win32 ------
1>Build started 4/27/2012 6:12:39 PM.
1>InitializeBuildStatus:
1>  Touching "Debug\string.unsuccessfulbuild".
1>ClCompile:
1>  strings.cpp
1>e:\users\hk3008\documents\visual studio 2010\projects\string\string\strings.cpp(15): warning C4101: 'reverseloop' : unreferenced local variable
1>e:\users\hk3008\documents\visual studio 2010\projects\string\string\strings.cpp(158): warning C4996: 'gets': This function or variable may be unsafe. Consider using gets_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1>		  e:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(277) : see declaration of 'gets'
1>e:\users\hk3008\documents\visual studio 2010\projects\string\string\strings.cpp(160): warning C4018: '<' : signed/unsigned mismatch
1>e:\users\hk3008\documents\visual studio 2010\projects\string\string\strings.cpp(199): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1>		  e:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(234) : see declaration of 'fopen'
1>e:\users\hk3008\documents\visual studio 2010\projects\string\string\strings.cpp(144): error C4716: 'reversenoloop' : must return a value
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.36
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I think I did the int main part right now to just get the last couple parts ironed out :)
but for my ignorent clarification below is a proper example correct?
#include <iostream>
using namespace std;
int main()
{
int function1();
int function2();
int function3();
}
int function1()
   code for function 1 ......
int function3()
   code for function 3 ......
int function3()
   code for function 3 ......

:) you guys are awesome I have learned more here then in class thank you all
  • 0

#11 Hydrokr0n1k

Hydrokr0n1k

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 57 posts
  • Learning:C++, JavaScript

Posted 27 April 2012 - 04:24 PM

as well with the reverse loop function alone works great
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
int reverseloop;
}
char STOP[265];
void reverse(char* a)// error: initializing argument 1 of ‘int reverse(char*)’ [-fpermissive]
{
int c = strlen(a) - 1;
for (; c >= 0; c--)
{
cout << a[c];
}
}
int reverseloop()
{
cout<<"Please digit an input to be reversed: "<<endl;
cin.getline(STOP,265);
reverse(STOP); //error: invalid conversion from ‘char’ to ‘char*’
// [-fpermissive]
system("pause");
return 0;
}
but in the collective multi function program its still putting errors in my debug, also I have tried searching up and down fow an un match "<" but am at a loss I even tried on ehre using F3 to find all < in the page and still cannot find one un matched
  • 0

#12 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 28 April 2012 - 01:23 AM

The main function is only provided as an easy way to get code to run there, when the program starts up. Forward declarations are useful to the compiler (so it knows what the funciton will return, be named, and parameter account). Placing it in main(), where the program starts *after* it is already compiled, will be defining functions within functions and will throw an error.

My concern was that you were telling the compiler it was returning an int (int reverse()), yet when you defined it, it was not returning an int ( void reverse()). This conflicts, as you're helping the compiler by giving it false information and it must abort the compilation.

#include <stdio.h>
void foobar(int, char); 

int main() {
   int number = 2;
   char letter = 'a';
   foobar(number, letter);
}

//matches the forward declaration: (return void, function name = foobar, accepts int, accepts char)
void foobar(int number, char letter) {
  
}

If the forward declaration is int foobar(int, char) then it is an incorrect signature for the function, and it cannot compile.

Note: Not to confuse you, but you can leave out the parameter names in the forward delcaration. All it needs to know is the datatype, such as int, char, char* , etc.

The declarations void foobar(int number, char letter) and void foobar(int, char) are equivalent. It helps the compiler know what the function is going to look like (in main) before it is actually defined (way below, in your foobar function code).

For example..

You can do this:
#include <stdio.h>
void foobar(int, char); //it knows what it looks like
int main() {
  foobar(1, 'a'); //so we can use it here 
}

//even though this is the end of the file here

Where is foobar defined? It doesn't have to be! You'll need to compile separately foobar.c (which will contain what foobar does, *but*, when compiling main.c (the above code), the compiler will know what foobar() returns, and accepts, so that it can validate it *even though none of its functional code is in that file at the time of its compilation*

As well: formatting code is very important. Your spacing (at least on here, not to say it wasn't in your editor) is nonexistent.

You can place all forward declarations in a header file: such as foobar.h, that's why you can use stdio or string.h, because the compiler will now know your standard input or string function declarations even though the string or stdio library is not within your main.c.

I've written this briefly at 2am, feel free to request more information. I will look over your other questions soon, but try to understand and fix your above code in a presentable manner.

Alexander.
  • 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.






Also tagged with one or more of these keywords: c++, string, realloc, ascii value

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download