C++ char to string acting funky [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is the code:
int main(){
string word= "word";
char ciphered[word.length()];
for(int i=0; i<word.length(); i++)
{
int current_position = (int) word[i];
int new_position = current_position + 2;
char this_char = (char) new_position;
ciphered[i] = this_char;
}
string str(ciphered);
cout << str << endl ;
}
When i run this it prints this:
But when i do this:
for(int i = 0; i<sizeof(ciphered); i++)
{
cout << ciphered[i] << endl ;
}
it prints out the same thing but without last three signs and that is correct
but whenever i try to convert this char array to string it adds these last three weird signs and i dont know why

First of all, this:
char ciphered[word.length()];
is not legal C++ code, though gcc may accept it. But second that you do not need really that char array, as you can access individual symbols with std::string itself:
string word= "word";
string ciphered( word.length(), ' ' );
for(int i=0; i<word.length(); i++)
{
ciphered[i] = word[i] + 2;
}
cout << ciphered << endl;
your code prints additional symbols because you did not put null terminator on C-style string and sent it through std::ostream which leads to UB and prints garbage that happens in memory after your char array until it suddenly finds null terminator or crash because of access of invalid memory.

Related

const char* pointer handling (C++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
Hi everyone I have a simple task in C++:
-> writing a program that takes a string from user input and loops over the characters in the string via a pointer.
If I understand correctly, then a previously declared string name; variable can also be accessed via const char*, implying that I can declare a pointer in the following manner: const char *pName = &(name[0]);. When printing the pointer, however, not the memory address but the actual variable is displayed in the terminal (see my code below). This prevents me from incrementing the pointer (see for loop).
Filename: countchar.cpp
#include <iostream>
using namespace std;
int main() {
string name;
std::cout << "Provide a string." << endl;
std::cin >> name;
const char *pName = &(name[0]);
cout << pName << endl;
// further downstram implementation
// int len = name.length();
// for(int ii = 0; ii < len; ii++){
// std::cout << "iteration" << ii << "address" << pName << endl;
// std::cout << "Character:" << *pName << endl;
// (pName+1);
// }
return 0;
}
Terminal output:
$ g++ countchar.cpp -o count
$ ./count
$ Provide a string.
$ Test
$ Test
As I am a quite a noob in regard to C++ help and an explanation are both highly appreciated (No material found online that solves my problem). Thanks in advance!
The operator << overloaded for a pointer of the type char * such a way that it outputs the string pointed to by the pointer.
So according to the assignment instead of these statements
const char *pName = &(name[0]);
cout << pName << endl;
you need to use a loop like
for ( const char *pName = &name[0]; *pName != '\0'; ++pName )
{
std::cout << *pName;
}
std::cout << '\n';

Program got stuck , not printing output [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am a beginner in C++. And I am trying to play with character array in C++. So, I have written this code.
#include <iostream>
using namespace std;
//Main Function
int main()
{
//Variable declaration
char First[30];
char Middle[30];
char Last[40];
//Array to store all names
char Name[70];
//Loop variables
int i = 0, j = 0;
//Reading all the name
cout << "Enter First name: ";
cin >> First;
cout << "Enter Middle name: ";
cin >> Middle;
cout << "Enter Last name: ";
cin >> Last;
//Copies all characters of Last name to fourth array
while (Last[i] != '\0')
{
Name[j] = Last[i];
i++;
j++;
}
//placing a comma in the fourth array and adding a space
Name[j] = ',';
j++;
Name[j] = ' ';
j++;
cout<<"Hello1\n";
//Copies all characters of First name to fourth array
i = 0;
while (First[i] != '\0');
{
Name[j] = First[i];
i++;
j++;
}
//Add a space
Name[j] = ' ';
j++;
cout<<"Hello2\n";
//Copies all characters of Middle name to fourth array
i = 0;
while (Middle[i] != '\0');
{
Name[j] = Middle[i];
i++;
j++;
}
Name[j] = '\0';
//Display the fourth array
cout << Name << endl;
}
The Problem with this code is that i want to print the Full Name of
Name[] array. But it is getting stuck after printing "Hello1" only.
It is not printing anything after "Hello1". It is taking input of all
three names ( in First[] , Middle[] and Last[] ) correctly. So, I
decided to trace out my code from line 1. I got to know that there is
some problem after first while loop as i am trying to print "Hello1"
and "Hello2". The problem is that it is printing "Hello1" correctly
but it is getting stuck for "Hello2". I think that some problem is in
2nd while loop. But i am not getting the error how could i resolve
this.
Please help me regarding this so that it could print the Full Name
correctly.
Ok so, the problem is your while loop, you made the mistake of put a ; in the end of it, which is making an infinity loop and never gets to the second hello.
//Copies all characters of First name to fourth array
i = 0;
while (First[i] != '\0'); // <- Here is your problem
Should be:
//Copies all characters of First name to fourth array
i = 0;
while (First[i] != '\0') { // <- Here is your problem
Edit
Thanks to Gilles-Philippe Paillé who pointed out, in the third while loop also has an semi-colon which should be removed :D

How to count lengths of contents of an array of pointers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Is it possible to count the length of the contents of an array of pointers:
For example
char *str[MAX] = {"kendrick", "lamar"};. the length of str[0] is 8 and str[1] is 5. Is there a way of getting these values.
You can verify if each pointer is NULL or not:
int count = 0;
for(int i = 0; i < MAX; i++)
if(str[i] != NULL)
count++;
printf("Count: %d\n", count);
As noted by others, it is not clear what you are exactly asking about.
In a hurry, I wrote the following code to give multiple outputs so you may find what you are looking for:
1- Length of each item by using strlen() function.(ilength)
2- Total length of the items by adding up individual lengths. (ilength).
3- Number of items in the array by counting non NULL (items).
int main()
{
const int MAX = 10;
char* str[MAX] = {"Hello", " World","!",""};
int ilength, length = 0, items = 0;
for(int i = 0; i < MAX; ++i)
if (str[i] != NULL)
{ ilength = strlen (str[i]);
// WARNING!!! ISO C++ forbids converting a string constant to 'char*'
cout << i << " item length is " << ilength << "\n";
length = length + ilength;
items += 1;
}
cout << "\nTotal length of all items is: " << length << "\n\n";
cout << "\nThere is/are " << items << " in the array.\n\n";
}
NOTE: If you use C++ compiler, pay attention to the warning:
WARNING!!! ISO C++ forbids converting a string constant to 'char*'
If you know the strings are all null-terminated, you can use strlen.
Your question is a bit confusing as it is not clear what length you want. Therefore for both possibilities:
Length of array in use:
char *str[MAX] = {"kendrick", "lamar"}; is an array of size MAX with two entries, which are pointers to strings. The compiler will initialize all other entries to zero, so counting how many entries of str are non-zero will give you that answer.
Length of the strings:
A string in C is null terminated. So for each entry of str that is not null you can advance and advance until you encounter a null character. That tells you the length of that entry.

issue counting number of letter occurrences in string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
When I input a string that starts with the letter 'a' the program fails to check for that letter and excludes it. If i input a string that has an 'a' just not first in string, it checks out.
Here is the complete problem:
Write a program that will read a line of text and output a list of all the letters that occur in the text together with the number of times each letter occurs in the line. End the line with a period that serves as a sentinel value or delimiting character.
The letters should be listed in the following order: the most frequently occurring letter, the next most frequently occurring letter, and so forth.
Use two arrays, one to hold letters and one to hold integers. You may assume that the input uses all lowercase letters. For example, the input do be go bo. Should produce output similar to the following:
Letter Numbers of Occurrence
o 3
b 2
d 1
e 1
Note: you can modify the implementation of the selection sort algorithm in the book to sort the array in descending order. You can use either string type or c-string type in your program.
Code:
#include<iostream>
#include<string>
using namespace std;
void sort(char letters[],int letter_count[])
{
for(int i=0; i<26; i++)
{
int max = i;
for(int j=i; j<26; j++)
{
if(letter_count[j] > letter_count[max]) max = j;
}
int temp = letter_count[i];
letter_count[i] = letter_count[max];
letter_count[max] = temp;
char local = letters[i];
letters[i] = letters[max];
letters[max] = letters[i];
}
}
int main()
{
string str;
char letters[26];
int letter_count[26] = {0 };
cout <<"Enter a line of text :";
getline(cin,str);
for(int i=0; i<str.length(); i++)
letter_count[str[i]-'a']++;
for(int i=0; i<26; i++)
letters[i] = static_cast<char> ('a'+i);
sort(letters, letter_count);
cout <<"Letter Numbers of Occurrence" << endl;
for(int i=0; i<26; i++) {
if(letter_count[i]!=0)
cout << letters[i] << " " << letter_count[i]<<endl;
}
return 0;
}
Problem found on line 20, where you try to swap letters[i] with letters[max]. That line should be
letters[max] = local;

Segmentation fault while passing string array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I went through similar question on stackoverflow but it did not solve my issue
I am trying to send string array as below
void manipulateString( char *);
int hashTable (int &, char * );
const int HTsize = 10;
int main()
{
const int size = 100;
char inputString[size];
cout << " Enter first names ( separate by a space ) \n ";
cin.getline(inputString,size);
manipulateString(inputString);
return 0;
}
void manipulateString (char *input)
{
int firstNamelen;
int hIndex=0,newIndex=0;
int totalName = 0;
char *firstname;
firstname = strtok(input, " "); // separate firstname
while (firstname != NULL)
{
firstNamelen = strlen(firstname);
hIndex = hashfunction(firstname,firstNamelen);
newIndex=hashTable(hIndex, firstname);
cout << "\n\n ( " << firstname << " ) is stored at index [" << hIndex << "] of hash table " << endl;
firstname = strtok(NULL, " " ); // next first name
}
}
When it reaches to void manipulateString (char *input) it gives segmentation fault. what is the issue?
Given that hashfunction and hashTable are not leading to a segmentation fault...
You can only read size-1 characters.
Check cin.fail() to see whether cin.getline was successfull. If not the string might not be NULL terminated. If the string is not NULL terminated, strlen or strtok might lead to a segmentation fault.