How iterate through char *str in C++? [closed] - c++

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 12 months ago.
Improve this question
#include <bits/stdc++.h>
using namespace std;
int main()
{
char *str;
gets(str);
int size = strlen(*(&str));
//How to iterate through this str which is acting like a string here
return 0;
}
//I'm trying to print each char in a new line.

Ignoring all the other problems, such as using an uninitialized pointer, using gets (it's so bad it's been removed from C and C++), including bits/stdc++.h, not using std::string and std::getline...
Using your size variable, you can use loop like this:
for(int index = 0 ; index < size ; ++index) {
std::cout << "character at index " << index << " is '" << str[index] << "'\n";
}
But note that your code will crash at gets and never get to this loop. Please find better learning material to get started with C++!
PS. To get your code to not crash, change char *str; to char str[10000];... Then that program should run and you are unlikely to accidentally cause a buffer overflow. Still, I repeat, get better learning material!

The character pointer str doesn't point to any char object and has not been initialized.
Second, the function gets has been deprecated in C++11 and removed in C++14.
A better way would be to use std::string instead as shown below:
#include <string>
#include <iostream>
int main()
{
std::string str;
//take input from user
std::getline(std::cin, str);
//print out the size of the input string
std::cout << str.size() << std::endl;
//iterate through the input string
for(char& element: str)
{
std::cout<<element<<std::endl;
}
}

Related

Initialize values in an array of strings 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 5 years ago.
Improve this question
Hello i'm from Indonesia. and i'm verry beginner on C++ programming. I have some problem when i learn about string on C++ . First i declared array of char and i want to initialize a value separately in different command. After i initialize the value my compiler say "Invalid Argument".
#include <iostream>
using namespace std;
int main() {
char Name[5];
Name = "Luke";
cout<<"Character 0 :"<<Name[0]<<endl;
cout<<"Character 1 :"<<Name[1]<<endl;
cout<<"Character 2 :"<<Name[2]<<endl;
cout<<"Character 3 :"<<Name[3]<<endl;
cout<<"Character 4 :"<<Name[4]<<endl;
return 0;
}
sorry if my english is bad :(
A character array(including a C string) can not have a new value assigned to it after it is declared.
The C++compiler interprets these assignment statements as attempts to change the address stored in the array name, not as attempts to change the contents of the array.
However you can use
char name[] = "Luke";
A char[] can't be assigned with a string with the = operator, except for on its initialization. That's why char Name[5]; Name = "Luke"; is invalid while char Name[5] = "Luke"; is.
Assigning strings to char[] can be done with strcpy() / memcpy()-like functions.
So you have two ways of action (assuming you want to work with char[]):
char Name[5] = "Luke";
char Name[5]; strcpy(Name, "Luke"); /* don't forget to #include <string.h>*/
Just for sake of education (since the other answers are on-point to answer the question), here's how I would have written your code to do nearly the same thing.
The changes demonstrate:
used a more appropriate container (a string instead of a char[])
checked for access overruns
moved "one unit of work" into its own subroutine
Code was compiled as C++17 with /usr/bin/clang++ -Weverything -Wno-c++98-compat --std=c++1z:
#include <cstddef>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
void PrintCharAtPos(string const& s, string::size_type pos);
int main() {
auto Name = string{"Luke"};
PrintCharAtPos(Name, 0);
PrintCharAtPos(Name, 1);
PrintCharAtPos(Name, 2);
PrintCharAtPos(Name, 3);
PrintCharAtPos(Name, 4);
return EXIT_SUCCESS;
}
void PrintCharAtPos(string const& s, string::size_type pos) {
if (pos < s.length())
cout << "Character " << pos << " : " << s[pos] << endl;
else
cout << "Character " << pos << " : (out of bounds)" << endl;
}

How to sort std::array with std::sort? [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 6 years ago.
Improve this question
#include <iostream>
#include <array>
#include <algorithm>
#include <cstring>
using namespace std;
int main() {
array<char, 20> test{"HelloWorld"}, tmp;
// method 1
tmp = test;
sort(tmp.begin(), tmp.begin() + strlen(tmp.begin()));
cout << "result: " << tmp.data() << endl;
// method 2
tmp = test;
sort(tmp.begin(), tmp.end());
cout << "result: " << tmp.data() << endl;
return 0;
}
std::array can be sorted with method 1. But it's so ugly.
I prefer method 2, but nothing can be returned. What's wrong with it?
The second method is sorting all the \0 elements to the front. (They are less than any of the other characters.
When you try and print it with .data() you get a char const* object back which to the stream class is treated like a C-String. Which is a null terminated string. Since the first character is a null it prints nothing.
You could fix with
auto cmp = [](char a, char b) { return a != '\0' && a<b; }
sort(tmp.begin(), tmp.end(), cmp);
This uses a comparator which sorts \0 at the end.
But as Jerry Coffin said in comments, std::array is not std::string - use the one which fits your needs (probably std::string in this case).
You're printing a C-String, which relies on the existence of a terminating null character: \0.
When you sort the entire array, you move that null character to the front, which tells your print functions that it is an empty string.
Thus, you have no choice but to use the uglier version. That being said, here's a safer way to write it which you may prefer:
sort(tmp.begin(), find(tmp.begin(), tmp.end(), '\0'));

I am new to c++ why is casting working in first case but not in second cout after masking one of the characters in char* [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 7 years ago.
Improve this question
why is casting working in the first case but not in second cout after masking one of the characters in char*
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
int n = 10;
char* ch = (char*) calloc(6, sizeof(*ch));
ch = strdup("ab");
cout << strlen(ch) << endl;
int* p = (int*) ch;
cout << (char*)p << endl;// works fine it prints "ab"
*p = *p & 65280;
cout << "cast not working\t" << (char*)p << endl; // it does not work here
free(ch);
return 0;
}
Written as hex, 65280 is 0x0000FF00. So, on common systems with int being 4 bytes, you have set ch[0] to be 0. This is a null terminator, so when you try to print the string, you see an empty string.
Note: writing to *p causes undefined behaviour by writing past the end of the allocated area too; strdup("ab") allocates 3 bytes. On common systems this probably will have no ill effect as heap allocations are done in chunks of a certain size.

C++ using arguments ARGV [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 8 years ago.
Improve this question
I want to take argv[(2 in this example)], store it into vector and use it later in program. The problem is that no operand matches those operands std::string == int. So does that mean that the app sees '-r' as int? I'm a bit confused here.
int main(int argc, char* argv[])
{
std::vector<std::string> argList;
cout<<"argc: "<<argc<<endl;
for(int i=2; i<=argc; i++)
{
argList.push_back(argv[i]);
}
if(argList.at(2) == '-r') cout<<" Good job ";
}
There are several issues with your program:
You iterate i until i == argc, that will attempt to construct a string from argv[argc], a NULL pointer due to the requirement by C and C++ standards that argv[argc] be 0 (NULL), see this SO question. argv is an array with argc pointers to null-terminated character strings (terminated by ASCII NUL, 0), the array itself is terminated with a NULL pointer (not counted in argc). Now, in C++ you can construct a string from a pointer to a null-terminated character string, but passing a NULL pointer to a string constructor results in undefined behavior, see this SO question, also see the list of std::string constructors here, you are implicitly using constructor (4) in that list (from c-string).
You start pushing onto argList with i==2, which means argList[0] will contain argv[2], you then reference argList.at(2), which would correspond to argv[4], this is not likely what you meant.
String literals use double quotes
I've corrected these and created a working program, click here
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
vector<string> argList;
cout << "argc: " << argc << endl;
for(int i=0; i < argc; ++i)
{
argList.push_back(argv[i]);
}
cout << "Program name is " << argList[0] << endl;
if(argc > 1) {
if(argList.at(1) == "-r") {
cout << " Good job, you supplied -r\n";
} else {
cout << "Unrecognized option " << argList[1]
<< "\nUsage: " << argList[0] << " -r\n";
}
}
return 0;
}
The problem is your use of single quotes in '-r'. You want double quotes here:
if(argList.at(2) == "-r") cout<<" Good job ";
The reason is that in C++, single quotes are used for characters only. There is such a thing as a "multi-byte character constant", which is what '-r' ends up being. This is something completely different from a string constant, which is what you want.

In short I really struggle with syntax, can somebody help me fix this? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
so i need to read in a file, then create a word count and a character count for each time the character appears using an array. each word ends with whitespace, comma, period, etc. also i need to put a tolower and an equation to set the letters to the right array with an x-'a' function or something like that.
list of errors from puTTy(crappy program i know but it's required)
project8.cpp: In function âint main()â:
project8.cpp:17: error: âfile1â was not declared in this scope
project8.cpp:18: error: expected â;â before âwhileâ
project8.cpp:36: error: expected â}â at end of input
#include <iostream>
#include <string>
using namespace std;
int in_word = false;
int word_count = 0;
char ch;
char low_case;
int char_count[26];
int i;
int main()
{
for (i=0; i<26; i++)
char_count[i]=0;
cin.get(file1.txt)
while('\n' !=(ch=cin.get(file1.txt)))
{
if (' ' == ch || '\n' == ch || '\t' == ch)
in_word = false;
else if (in_word == false)
{
in_word=true;
word_count++;
}
else low_case=tolower(ch);
char_count[int(low_case)-int('a')]++;
}
cout << file1.txt;
cout << words << " words" << endl;
for (i=0; i<26; i++)
if(count[i] !=0)
cout << count[i] << " " << char(i+'a') << endl;
}
The first problem is that you haven't declared file1. It is somewhat unclear what file1.txt really is meant to be: The way it is written, it seems to be an object of type with a member called, txt of type char* or char[N] (with a constant N). From the looks of it, you actually wanted to open a file named file1.txt. This would look like so:
std::ifstream in("file1.txt");
After that you would, of course, use in instead of std::cin to read from the file. For example you could use
for (char c; in.get(c); ) {
// ...
}
to read each individual character of the file and process it appropriately.
Let's play compiler!
You cannot name a variable file1.txt, call it file1
Also, you forgot the semi-colon ; at the end of the line, so
cin.get(file1.txt)
should be
cin.get(file1);
I don't quite know where you are defining this variable, so you may be missing a declaration like
const char* file1="file1.txt";
Furthermore, you start trying to access some variable count after your for-loop here:
count[i]
Did you mean to use char_count?