I'm trying to make a program that reads in a "string" (into a char *) from user input, then using cstring, it gets the length of what the char * is pointing to. From what I understand, char * is a pointer. A reference to a pointer will be redirected to what it is pointing to. In this case, word should point to 4321, and when word gets output, what it is pointing to is what actually gets output. Also, strlen should read up until the \0, which in this case the string should be 4321\0, so why does it segmentation fault?
Desired result:
Enter a string: 4321
4321
(length of 4321)
Program:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char *word;
int len;
cout << "Enter a string: ";
cin >> word;
len = strlen(word); //why does this cause a segmentation fault?
cout << word << endl;
cout << len << endl;
return 0;
}
You need
char word [256] ; // or something
Better yet
std::string word ;
cout << word.length () ;
In your code "word" is just a pointer. If you mean to write something directly into a pointer, first you must assign a valid memory address to it. If it is not important for you that "word" is a pointer then a char array will suffice.
Related
So I have an assignment that uses char arrays instead of strings. You assign the array from a .txt file and ifstream. A function I have to write is to concatenate the array with another array. However, the array breaks if I add any extra char after the initial word, even though I initialized the array with plenty of space.
input.txt
Hi
main.cpp
#include <iostream>
#include <fstream>
ifstream in("input.txt");
int main()
{
char A[50];
in >> A;
cout << A << endl; // expecting to print "Hi"
A[2] = 't';
cout << A << endl; // expecting to print "Hit"
in.close();
return 0;
}
I expected to see:
Hi
Hit
Instead it prints:
Hi
HitpB
Any help?
you forgot to add '\0' char in zero terminated char array, after you replaced value with index 2.
I was trying to hold the text entered by user inside an Char array but it does not end up well. I tried this method but i think it deleted after c++ 11.
Here's my code :
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char sentence[2];
cout << "Enter your sentences : ";
gets_s(sentence);
cout << sentence << endl;
system("PAUSE");
return 0;
}
It gives overload error and doesnt works.
Chances are you are trying to get the string literal that is longer than 2 characters yet not being able to insert it into your buffer of:
char sentence[2];
Increase the buffer size to something more acceptable:
char sentence[255];
That being said in C++ you should prefer std::string to character array and std::getline to gets_s.
I have written a C++ Function which can be represented as below:
All it does is take a string (this is where it crashes) and reverse it.
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
cout<<"Enter a string: "<<endl;
char *str;
gets(str);
cout<<"Reversed String is: ";
for(int i=strlen(str)-1;i>=0;i--)
cout<<(str[i]);
return 0;
}
I guess there's some kind of memory access violation.
Any clue why this doesn't work?
Error: Segmentation fault (core dumped)
In c++ there is way more easier and less error prone solution to this problem via std::reverse from algorithm. Also its easier to use std::string.
#include <iostream>
#include <algorithm>
int main ()
{
std::string input;
std::cout << "Enter string to reverse: ";
std::cin >> input;
std::reverse(input.begin(),input.end());
std::cout << "Reversed string: " << input << std::endl;
return 0;
}
If you have to do it via char arrays, try this (you dont even need dynamic memory allocation)
#include <iostream>
#include <algorithm>
#include <cstring>
int main ()
{
char input[1024];
puts("Enter string to reverse: ");
fgets(input, 1024, stdin);
std::reverse(input, input + strlen(input));
printf("Reversed string: %s", input);
return 0;
}
Your code isn't c++ style and I recommend you take a look at the answer from Filip (https://stackoverflow.com/a/45903067/4386427)
I'll just address what goes wrong with your code.
When you do
char* str;
all you get is a pointer that can point to a char. You don't get any memory for holding a char. Further the value of the pointer variable str is uninitialized.
So when you do
strlen(str)
you read an uninitialized variable and try to treat this uninitialized value as a C-style string. That is undefined behavior and is very likely to cause a program crash.
You need to make sure that str is initialized before using it. As you want dynamic memory, you could do:
char *str;
str = new(char[100]); // Initialize str to point to a dynamic allocated
// char array with size 100
...
...
delete(str);
But again - I wouldn't use this style in c++ code
I created a program that the user enters a string. But i need to count how many letters are in the string. The problem is im not allowed to use the strlen()function. So i found some methods but they use pointers but im not allowed to use that yet as we havent learned it. Whats the best way to do this in a simple method? I also tried chars but i dont have luck with that either.
#include <iostream>
using namespace std;
string long;
string short;
int main()
{
cout << "Enter long string";
cin >> long;
cout << "Enter short string";
cin >> short;
return 0;
}
I need to get the length of long and short and print it.
I am trying to use it without doing strlen as asked in some previous questions.
Do you mean something like this?
//random string given
int length = 1;
while(some_string[length - 1] != '\0')
length++;
Or if you don't want to count the \0 character:
int length = 0;
while(some_string[length] != '\0')
length++;
You can count from the beginning and see until you reach the end character \0.
std::string foo = "hello";
int length = 0;
while (foo[++length] != '\0');
std::cout << length;
If you use standard cpp string object I think the best way to get length of your string is to use method:
long.size();
It gives you number of characters in string without end string character '\0'. To use it you must include string library :
#include <string>
If you decide to use char table you can try method from cin:
char long_[20];
cout << "Enter long string\n";
int l = cin.getline(long_,20).gcount();
cout << l << endl;
gcount()
Here is my code:
#include <iostream>
using namespace std;
int main(){
char inp[5], out[4];
cin >> inp >> out;
cout << inp << endl;
cout << out << endl;
system("pause");
return 0;
}
when I type:
12345
6789
It gives me:
6789
Why I failed to save the 5 words char array 'inp' and it showed nothing? The second input looks normal though. However, when I set out[3] or out[5], it seems to work alright? It seem that two char array of [5] then followed by [4] would cause problem...
I see that you enter (type) 1234567890 characters to input data for inp[5] - it is a problem because imp array is able to store 4 characters and null-terminator. When cin >> inp store more than 4 characters to inp array it leads to problem with data (somthing like undefined behaviour). So solution can be in allocation more memory for data, e.g.:
#include <iostream>
using namespace std;
int main(){
char inp[15], out[15]; // more memory
cin >> inp >> out;
cout << inp << endl;
cout << out << endl;
system("pause");
return 0;
}
When you read into a character array the stream keeps reading until it encounters whitespace, the stream is not aware of the size of the array that you pass in so happily writes past the end of the array so if your first string is longer than 4 characters your program will have undefined behaviour (an extra character is used after your input for the null terminator).
Fortunately c++20 has fixed this issue and the stream operators no longer accept raw char pointers and only accept arrays and will only read up to size - 1 characters.
Even with c++20 the better solution is to change your types to std::string which will accept any number of characters end even tell you how many characters it contains:
#include <iostream>
int main(){
std::string inp, out;
std::cin >> inp >> out;
std::cout << inp << "\n";
std::cout << out << "\n";
return 0;
}
Its because, in memory layout of computer out[4] is laid out first and then inp[5]. Something like this:
out[0],out[1],out[2],out[3],inp[0],inp[1],inp[2],inp[3],inp[4]
So, when you write 6789 in out[4], you are overflowing null character to inp[0]. So, inp becomes NULL.