Answer the question
In order to leave comments, you need to log in
How to correctly split a string by spaces and add it to an array?
You need to split the input string by spaces and put the resulting substrings into an array.
I did it like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
char input[] = "Hello world! I am Alex! I'm from Russia\0";
char *p = input;
int index = 2;
char **arr = new char*[index];
int n = 0, m = 0; // Индексы для управления массивом
// n - индекс подстроки в массиве
// m - индекс символа в подстроке
while (*p) {
if (*p != ' ' && *p) {
arr[n][m] = *p;
m++;
}
else {
arr[n][m] = '\0';
m = 0;
// Увеличение массива
char **temp = new char*[index];
for (int i = 0; i < index; i++) {
temp[i] = arr[i];
}
arr = new char*[index++];
for (int i = 0; i < index-1; i++) {
arr[i] = temp[i];
}
delete[] temp;
}
p++;
// Вывод подстрок
for (int i = 0; i < index; i++)
{
cout << arr[i] << endl;
}
delete[] arr;
return 0;
}
Answer the question
In order to leave comments, you need to log in
Well, if you’re right on the space, and if it’s really in C ++, then here:
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
std::istringstream input{ "foo bar baz qux" };
std::vector<std::string> result;
// extract substrings one-by-one
while (!input.eof()) {
std::string substring;
input >> substring;
result.push_back(substring);
}
// print all the extracted substrings
for (const std::string& substring : result) {
std::cout << substring << std::endl;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question