char array length c++ <i'm newcomer> - c++

i'm newcomer.
i need size of input.
#include <iostream>
using namespace std;
int main()
{
int a,b,n;
char c[100];
cout<<"insert number of adjective : " ;
cin>>a;
for(b=0;b<a;b++)
{
cin>>c;
int length = sizeof(c);
cout<<length<<endl;
cout<<c<<endl;
}
return 0;
}
please help me for find the size lenght c
hamed

First off, never (as in really never) use std::cin >> array; wher e array is a char array (or a pointer to the start of such an arry) unless you have first set up the maximum amount of data which can be read by setting the stream's width(). Any teacher showing you how to use std::cin >> array; without advising to use width() has to be corrected!
You can, e.g., use
#include <cstring> // NOT <string>...
// ...
char c[100];
std::cin.width(sizeof(c));
if (std::cin >> c) {
std::size_t n = std::strlen(c);
// ...
}
to limit the number of character to be read to sizeof(c) - 1 (the -1 is there because a terminating null character is also read). Once you have successfully read your input (you also need to always check that input was actually successful) you can use strlen(c) to determine the number of characters read.
Personally, I read very rarely formatted data into a char array in real code. I normally simply read a std::string which is much easier and safer to use. I'd consider dealing with input to built-in array a somewhat more advanced topic.

you can use vector
#include <vector> ...
int n;
cin >> n;
vector<int> vec(n);
...
int size_of_vector = vec.size();
...

#include <string>
using namespace std;
int main()
{
////////////////////input
int a,b,n,i;
char c[100];
cout<<"insert number of adjective : " ;
cin>>a;
for(b=0;b<a;b++)
{
cin>>c;
n = strlen(c) ;
cout<<n<<endl;
/////////////////////////processing
if(c[n]=='r')
{
cout<<"ok";
}
/////////////////////////output
cout<<c<<endl;
}
}

This map help then.
/* strlen example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szInput[256];
printf ("Enter a sentence: ");
gets (szInput);
printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput));
return 0;
}

first use: #include <string>
second write: int length = strlen(c); // insted of int length = sizeof(c);
strlen() function find length of string but you must include string library.

Related

count letters in a string c++

I am trying to write a function that counts the number of characters in a string excluding spaces. However, the output is always wrong so there is something wrong with my code.
There is something wrong with my code but I can't figure it out. Please help me with my programming homework.
#include <iostream>
#include <bits/stdc++.h>
#include <stdio.h>
#include <ctype.h>
using namespace std;
int countLetters (char s[], int size_s){
int isLetter = 0;
for(int i =0; i<size_s;i++){
if (isalpha(s[i])){
isLetter ++;
}
}
return isLetter;
}
int main (){
char s[100];
gets(s);
int n = sizeof(s)/sizeof(s[0]);
cout << countLetters(s,n);
}
Here is an example of the wrong output:
hi
10
PS C:\Users\user\OneDrive\Desktop\cpp practical> cd "c:\Users\user\OneDrive\Desktop\cpp practical\" ; if ($?)
{ g++ count_letters.cpp -o count_letters } ; if ($?) { .\count_letters }
hi
6
PS C:\Users\user\OneDrive\Desktop\cpp practical> cd "c:\Users\user\OneDrive\Desktop\cpp practical\" ; if ($?)
{ g++ count_letters.cpp -o count_letters } ; if ($?) { .\count_letters }
hi
10
PS C:\Users\user\OneDrive\Desktop\cpp practical>
To begin with, I think your information source, like PepijnKramer, said in the comments, is a bit old. There are much easier data types you can use to complete this problem like std::string below.
First of all, your code is redundant in its header files: #include <bits/stdc++.h> is a nonstandard header, and you already have all the libraries you need.
Secondly, your main problem comes from the lines
char s[100];
gets(s);
int n = sizeof(s)/sizeof(s[0]);
You see, you first create a char array called s with 100 elements. However, you never give them an initial value, so the random garbage that came with the initialization stays. However, C++ also does not reset the values, so some of them may be randomized into letters. Then, you just use gets() to input the string. However, gets() only fills the array s with the number of characters you entered. Therefore, if you do not enter 100 characters, the random garbage that still can be a letter remains. Finally, when you do the size with the integer n, it turns out the result is always 100 because you defined s to have 100 elements, so when you run the function, you still iterate over the garbage in the array s. Therefore, depending on chance of what the garbage includes, your output is incorrect. To solve this, you can either you make sure to initialize it by
char s[100] = { };
Or switch a datatype. Here is a correct solution using std::string:
#include <bits/stdc++.h>
using namespace std;
int countLetters (string a, int size_s){
int isLetter = 0;
for (int i = 0; i < size_s; i++) {
if (isalpha(a[i])){
isLetter++;
}
}
return isLetter;
}
int main () {
string s;
getline(cin, s);
cout << countLetters(s, s.length());
}

C++ - How do I frequency count characters?

I need to write code to store the unique characters and their frequencies in a dynamic array. I need to increase its size as new data comes in. New data in this case will be a new character that is encountered. The algorithm I have in mind is to check the list of known characters every single time I read from the given string. If it is a new character I need to increase the array size by 1. If it is not a new character I will increase its frequency. It is an array of struct letter (in the code below). The problem is that, I spent quite a lot of time with this and had issues with implementing it. So the question is how can I exactly implement it? Thank you spending time to help.
#include <iostream>
#include <string>
#include <bitset>
#define ARR_LEN(arr) sizeof(arr)/sizeof(arr[0])
using namespace std;
struct unique_char {
char character;
int frequency;
};
int main() {
int char_count;
string str;
getline(cin, str);
struct unique_char* chars = new struct unique_char[100];
system("PAUSE");
exit(0);
}
As mentionned in the comments, using std::map makes this fairly straightforward.
One of the "fun" things about map is that the indexing operator creates new values "on demand" with a initial value of 0 for ints. So the actual code is essentially one line: chars[c] += 1;
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main() {
map<char, int> chars;
string str;
getline(cin, str);
for(char c: str) {
chars[c] += 1;
}
for(auto [character, frequency]: chars) {
cout << character << " : " << frequency << "\n";
}
}
N.B. There is one major difference between this and #ThomasMatthews's answer:
The map will only contain the characters that have been seen, whereas the array will contain 0s for all characters that were never hit. Which approach you use should be based on which of the two are more useful to you.
Using an array makes things straight forward:
unsigned int frequencies[256] = {0};
while (std::getline(std::cin, str))
{
const size_t length = str.length();
for (unsigned int i = 0; i < length; ++i)
{
const char c = str[i];
++frequencies[c];
}
}
Although, you may want to improve efficiency:
const size_t BUFFER_SIZE = 1024u * 1024u;
//...
char buffer[BUFFER_SIZE] = {0};
while (std::cin.read(&buffer[0], BUFFER_SIZE)
{
const size_t chars_read = cin.gcount();
for (unsigned int i = 0; i < chars_read; ++i)
{
const char c = buffer[i];
++frequencies[c];
}
}
The above code uses block reading to improve input performance. No scanning for newline characters, just read straight into memory. Determine the frequencies from the characters in memory.
Edit 1: unsigned char
From the comments, an unsigned char may be a safer data type than char because char can be signed. This may be an issue when accessing the array slots because a signed char could be negative and negative indices are usually a bad thing. When you run it, if there are issues, replace the char type with unsigned char.

Keep output and input from alternating?

I am very new to coding, and have been practicing with some easy problems at codeforces.com. I was working on this problem, but it seemed to be asking for the input (all at once) yielding the output (all at once). I can only figure out how to get one output at a time.
Here are the basic instructions for the problem:
Input
The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
output
word
l10n
i18n
p43s
Here is my code:
#include <iostream>
#include <string>
using namespace std;
void wordToNumbers(string word){
int midLetters = word.length();
char firstLetter = word.front();
char lastLetter = word.back();
cout <<firstLetter <<(midLetters-2) <<lastLetter <<endl;
}
int main(){
string wordInput;
string firstNum;
getline(cin,firstNum);
int i = stoi(firstNum);
for(i>=1; i--;){
getline(cin,wordInput);
if (wordInput.length() > 10){
wordToNumbers(wordInput);
} else {
cout <<wordInput <<endl;
}
}
return 0;
}
it's perfectly fine to read and print output for the lines one by one.
Exactly your solution accepted: http://codeforces.com/contest/71/submission/16659519
I'm also a beginner in c++. My idea would be to save every line first in a buffer and then write everything to std::cout.
I use a std::vector as the buffer, cause IMO it is simple to understand and very useful in many cases. Basically it is a better array. You can read more about std::vector here.
#include <iostream>
#include <string>
//for use of std::vector container
#include <vector>
using namespace std;
void wordToNumbers(string word){
int midLetters = word.length();
char firstLetter = word.front();
char lastLetter = word.back();
cout <<firstLetter <<(midLetters-2) <<lastLetter <<endl;
}
int main(){
string wordInput;
string firstNum;
//container for buffering all our strings
vector<string> bufferStrings;
getline(cin,firstNum);
int i = stoi(firstNum);
//read line by line and save every line in our buffer-container
for(i>=1; i--;){
getline(cin,wordInput);
//append the new string to our buffer
bufferStrings.push_back(wordInput);
}
//now iterate through the buffer and write everything to cout
for(int index = 0; index < bufferStrings.size(); ++index) {
if (bufferStrings[index].length() > 10){
wordToNumbers(bufferStrings[index]);
} else {
cout <<bufferStrings[index] <<endl;
}
}
return 0;
}
Probably this is not the best or most beautiful solution, but it should be easy to understand :)

"Segmentation Fault [Core Dumped]" while initializing 2d array of char dynamically [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I want to get an array of strings from user. I am getting the exception "Segmentation Fault [Core Dumped]" on runtime.
#include <iostream>
#include <iomanip>
#include <math.h>
#include <string.h>
using namespace std;
int main() {
long testCaseCount = 0;
cin >> testCaseCount;
char **testCases;
*testCases = new char[testCaseCount];
for(int i=0;i<testCaseCount;i++) {
cin >> testCases[i];
}
}
You're not allocating space for each string being read. The following are two ways to do what you're trying, the first being the mostly-C approach you seem to want to take, the second fully exploiting the standard library for all its glory.
Both of the following examples should result in the same test strings given the same input content. The first resizes with each new additional char arrival. Though it may seem overkill, it is actually simpler than maintaining a geometric growth algorithm.
That said, here is the code. I leave it to you to decide which of these is more prone to errors and bugs (and I just wrote both online, so there are bound to be bugs regardless).
The Hard Way
#include <iostream>
#include <cstdlib>
#include <cctype>
using namespace std;
int main()
{
unsigned int testCaseCount = 0;
char **testCases = NULL;
// read and validate we received a count greater than zero
if (cin >> testCaseCount && testCaseCount > 0)
{
// allocate + nullinitialize that many pointers
testCases = new char *[testCaseCount]();
for (unsigned int i = 0; i < testCaseCount && cin; ++i)
{
// skip leading whitespace
char ch;
while (cin.get(ch) && std::isspace(ch));
if (cin)
{
// read chars until whitespace or EOF. vsize
// represents the size of the allocated buffer
char *value = new char[1]();
size_t vsize = 1;
while (cin.get(ch) && !std::isspace(ch))
{
// allocate larger buffer
char *tmp = new char[vsize + 1];
// copy in old content to new buffer
std::copy(value, value + vsize, tmp);
std::swap(value, tmp);
// save new char and terminator
value[vsize - 1] = ch;
value[vsize++] = 0;
// delete old buffer
delete[] tmp;
}
// save accumulated value.
testCases[i] = value;
}
}
}
// show test cases
for (unsigned int i = 0; i < testCaseCount && testCases[i]; ++i)
std::cout << testCases[i] << '\n';
// cleanup
for (unsigned int i = 0; i < testCaseCount && testCases[i]; ++i)
delete[] testCases[i];
delete[] testCases;
return 0;
}
The Easy Way
#include <iostream>
#include <iterator>
#include <vector>
#include <string>
int main()
{
unsigned int testCaseCount = 0;
std::vector<std::string> testCases;
if (cin >> testCaseCount)
{
std::string s;
while (testCaseCount-- && cin >> s)
testCases.emplace_back(s);
}
// show test cases
for (auto const& s : testCases)
std::cout << s << '\n';
return 0;
}
You have to write at least as
char **testCases = new char *;
*testCases = new char[testCaseCount];
Though it is not clear why you do not want to write simply as
char *testCases = new char[testCaseCount];
And do not forget to delete what was allocated with the operator new.
Take into account that it is not "an array of strings". It is simply an array of characters. If you want to get an array of strings you should at first decide what will be the maximum length of a string.
First you need to allocate space for the pointers to the first character of each string:
char** testCases = new char*[testCaseCount];
Then you'll need to allocate space for each string:
testCaseCount[i] = new char[maxStringLength];
cin >> testCaseCount[i];
However, this is dangerous-- cin won't do any bounds checking. You really should use std::string.
Getting Exception "Segmentation Fault [Core Dumped]" on runtime.
You have undefined behavior by dereferencing an undefined pointer in:
*testCases = new char[testCaseCount];
Objective: I want to get an array of strings from user
In c++ you use an std::string and an std::vector:
#include <iostream>
#include <string>
#include <vector>
int main() {
long testCaseCount = 0;
std::cin >> testCaseCount;
std::vector<std::string> testCases(testCaseCount);
for (auto& s : testCases)
std::cin >> s;
}
Live demo

Scanning ASCII value of each character of a string

Is there anyway , if I enter any string , then I want to scan ASCII value of each character inside that string , if I enter "john" then I should get 4 variables getting ASCII value of each character, in C or C++
Given a string in C:
char s[] = "john";
or in C++:
std::string s = "john";
s[0] gives the numeric value of the first character, s[1] the second an so on.
If your computer uses an ASCII representation of characters (which it does, unless it's something very unusual), then these values are the ASCII codes. You can display these values numerically:
printf("%d", s[0]); // in C
std::cout << static_cast<int>(s[0]); // in C++
Being an integer type (char), you can also assign these values to variables and perform arithmetic on them, if that's what you want.
I'm not quite sure what you mean by "scan". If you're asking how to iterate over the string to process each character in turn, then in C it's:
for (char const * p = s; *p; ++p) {
// Do something with the character value *p
}
and in (modern) C++:
for (char c : s) {
// Do something with the character value c
}
If you're asking how to read the string as a line of input from the terminal, then in C it's
char s[SOME_SIZE_YOU_HOPE_IS_LARGE_ENOUGH];
fgets(s, sizeof s, stdin);
and in C++ it's
std::string s;
std::cin >> s; // if you want a single word
std::getline(std::cin, s); // if you want a whole line
If you mean something else by "scan", then please clarify.
You can simply get the ascii value of a char by casting it to type int:
char c = 'b';
int i = c; //i contains ascii value of char 'b'
Thus, in your example the code to get the ascii values of a string would look something like this:
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
int main()
{
string text = "John";
for (int i = 0; i < text.size(); i++)
{
cout << (int)text[i] << endl; //prints corresponding ascii values (one per line)
}
}
To get the corresponding char from an integer representing an entry in the ascii table, you just have to cast the int back to char again:
char c = (char)74 // c contains 'J'
The code given above was written in C++ but it basically works the same way in C (and many other languages as well I guess)
There is no way to turn a string of length 'x' into x variables. In C or C++ you can only declare a fixed number of variables. But probably you don't need to do what you are saying. Perhaps you just need an array, or most likely you just need a better way to solve whatever problem you are trying to solve. If you explain what the problem is in the first place, then I'm sure a better way can be explained.
Ya,I think there are some more better solutions are also available but this one also be helpful.
In C
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(){
char s[]="abc";
int cnt=0;
while(1){
if(s[cnt++]==NULL)break;
}
int *a=(int *)malloc(sizeof(int)*cnt);
for(int i=0;i<cnt;i++)a[i]=s[i];
for(int i=0;i<cnt-1;i++)printf("%d\n",a[i]);
return 0;
}
In C++
#include <iostream>
#include <string>
using namespace std;
int main(){
string s="abc";
//int *a=new int[s.length()];
//for(int i=0;i<s.length();i++)a[i]=s[i];
for(int i=0;i<s.length();i++)
cout<<(int)s[i]<<endl;
return 0;
}
I hope this one will be helpful..
yeah it's very easy ..just a demo
int main()
{
char *s="hello";
while(*s!='\0')
{
printf("%c --> %d\n",*s,*s);
s++;
}
return 0;
}
But make sure your machine is supporting the ASCII value format.
In C every char has one integral value associted with it called ASCII.
Using %d format specifier you can directly print the ASCII of any char as above.
NOTE: It's better to get good book and practice this kind of program yourself.