Copy structure with char array to char array [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 5 years ago.
Improve this question
I have a problem as the topic.
My code:
struct message{
char sender_name[20];
char dest_name[20];
char content_message[256];
};
int main() {
message tmp;
printf("Enter your name\n");
std::cin>>tmp.sender_name;
printf("Enter dest name\n");
std::cin>>tmp.dest_name;
printf("Enter message to %s \n",tmp.dest_name);
std::cin>>tmp.content_message;
memcpy(&buffer, &tmp,sizeof(tmp));
printf("MEASAGE: %s\n",buffer);
return EXIT_SUCCESS;
}
In buffer is only tmp.sendername and I don't know how to fix it.
I read a lot of topics but I can't fix it.
Please for help.

It copies everything, you're just accessing it wrong:
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
struct message{
char sender_name[20];
char dest_name[20];
char content_message[256];
};
char buffer[sizeof(message)];
int main() {
message tmp;
printf("Enter your name\n");
std::cin>>tmp.sender_name;
printf("Enter dest name\n");
std::cin>>tmp.dest_name;
printf("Enter message to %s \n",tmp.dest_name);
std::cin>>tmp.content_message;
memcpy(&buffer, &tmp,sizeof(tmp));
message *cpy = reinterpret_cast<message*>(buffer);
printf(
"sender_name: '%s\n'"
"dest_name: '%s\n'"
"content_message: '%s\n'",
cpy->sender_name,
cpy->dest_name,
cpy->content_message
);
return EXIT_SUCCESS;
}
Test:
g++ buffer.cc && printf '%s\n' foo bar baz | ./a.out
Output:
Enter your name
Enter dest name
Enter message to bar
sender_name: 'foo
'dest_name: 'bar
'content_message: 'baz
'
Also, BTW, probably not a good way to read into char buffers. There can hardly be any range checking with this API (given that it also appears to work with pointers as opposed to just arrays) which would make it about as unsafe as gets. It also doesn't appear to be documented (http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt) and out of gcc and clang, only gcc accepts it.

Related

how to write correctly into multidimentional char array unknown amount of values but fixed amound of chars [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
I'm sick and tired of solving why my ch[0] is of value "Thomas EdisonÇ#", when it should be "Thomas Edison"
int main(){
using namespace std;
ifstream in("U2.txt");
int n;
in>>n; //n=rows, so in every line there will be "name surname", time, money
char ch[n][21]; //I'm trying to get Name+Surname which must be 20 char long
in.read(ch[0], 20);
cout << ch[0]; //but getting Thomas EdisonÇ#
return 0;}
It works on one dimentional ch[21], but there's gonna be lots of values so I want to use ch[n][21]
Any other out of my box solution is welcome, I'm tired
You are forgetting that C strings need to be nul terminated
in.read(ch[0], 20);
ch[0][20] = '\0'; // add the nul terminator
cout << ch[0]; // now correct output

Char seperated by a decimal into a double c++ [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
I am passing a string variable (std::string) and iterating through the string character by character. Whenever I run into a decimal, I want to combine the previous position on the string (i.e 2) and the next position in the string (i.e 5) into a double. So how would I go about making the char 2, char . , char 5 into one whole value (2.5)?
std::double x;
std::string varibleName = "4 5 7 2.5";
for (int i = 0; i < variableName.length(); i++) // iterates through variableName
{
if (variableName[i] == '.'){ // if the current position of the iteration is a decimal, I want to grab the char before the decimal and the char after the decimal so I can combine all three positions of the string making it 2.5 and not 25.
}
}
Well, you are wildly overthinking it. The C++ library provides std::stof, std::stod, std::stold that does exactly what you want. Convert a string like "2.5" to a float, double or long double, e.g.
#include <iostream>
int main (void) {
std::string s = "2.5";
double d = std::stod(s);
std::cout << d << "\n";
}
Example Use/Output
$ ./bin/stodex
2.5
Look things over and let me know if you have further overthinking questions.
Note that giving an example, code snips, and error logs make troubleshooting a lot easier :)
It sound like you have some input like "2.1" and need to convert it to a double like 2.1?
If that is the case you can use the <cstdlib> atof function.
Example:
/* atof example: sine calculator */
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atof */
#include <math.h> /* sin */
int main ()
{
double n;
char buffer[256];
printf ("Enter degrees: ");
fgets (buffer,256,stdin);
n = atof (buffer);
printf ("You entered %s which is a double like %f\n" , buffer, n);
return 0;
}

Just input a number in cpp [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
I'm need to create id just number. For example: 12345678
If user inputs fail( contain char), delete char immediately.
For example: 123a =>input gain!
Please help me!
I think this is what you are looking for:
#include <iostream>
#include <string>
#include <cctype>
int main () {
std::string input;
bool valid;
do {
valid = true;
std::cin >> input;
for (char c : input)
if (! std::isdigit( static_cast<unsigned char>(c) ) )
valid = false;
} while (! valid);
// Here the string is guaranteed to be valid
}
Be aware though, that whatever you are trying to do, this does not look like the proper way to do it. There are ways to read numbers in c++, and this is not what I would recommend.

How to change permissions of a file in Linux with C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to change the permissions of a file with C++ in Linux. The user has to enter the permissions using this syntax: "Please enter the permissions: rwx-w-r--" in the terminal.
Thanks for helping.
#include <sys/types.h>
#include <sys/stat.h>
int main() {
chmod("./myfile", S_IRWXU); // enables owner to rwx file
}
See man 2 chmod for more details.
If the question is how to parse a 9 character string of the form "rwx-w-r--", realize that the permissions are encoded in an int as bits. If a bit is on, that permission is on. The following code will take your string, turn it into bits, in the obvious way...no validation etc. is done. It's a proof-of-concept.
#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>
int parse(char* perms) {
int bits = 0;
for(int i=0; i<9; i++){
if (perms[i] != '-') {
bits |= 1<<(8-i);
}
}
return bits;
}
int main() {
char perms[]="rwx-w-r--";
int exmp = S_IRWXU | S_IWGRP | S_IROTH;
printf("%d %d\n", parse(perms), exmp);
// outputs 468 468
}

count a specific word in string in c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am new at programming. please help me to solve this program :
the program gets a string and a word , and check the number of occurrences of that word in the string using c\c++.
thank you vary much
this is my first post.
If you want to find number of occurrence of a pattern or word in a string you can use KMP algorithm.
It will give you the total number of occurrences of a word in a string.
Example :
string = "abaabcabaabd"
word = "aba"
Output will be 2, abaabcabaabd
Complexity : O(n) where n is the length of the string
UPDATE 1:
I don't know actually what problem you are talking about :(
But if you want to count number of words like this example :
string : hi how are you how are hi how
word : how
how contain 3 times. hi *how* are you *how* are hi *how*
If your problem is like this, then this program will do :
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str,word;
getline(cin,str);
getline(cin,word);
stringstream ss(str);
int cnt=0;
while(ss>>str)
{
if(str==word)
cnt++;
}
cout<<cnt<<"\n";
return 0;
}
UPDATE 2:
Using pointer to solve same problem :
#include <bits/stdc++.h>
using namespace std;
int main()
{
char str[100],word[100];
gets(str);
gets(word);
char *token=strtok(str," ");
int cnt=0;
while(token!=NULL)
{
if(strcmp(token,word)==0)
cnt++;
token=strtok(NULL," ");
}
cout<<cnt<<"\n";
return 0;
}