[英]Truncating and removing characters from char array C++
我基本上有一个看起来像这样的txt
文件...
High Score: 50
Player Name: Sam
Number Of Kills: 5
Map
Time
我想将:
或Map
and Time
之后的空白存储在一个数组中,并将所有内容存储在另一个数组中。 对于Map
和Time
,此后没有任何内容,因此我想将空白存储为null
。
到目前为止,我已经设法读取所有这些信息并将其存储到temp
数组中。 但是,我感到麻烦的是分离。 这是我的代码:
istream operator >> (istream &is, Player &player)
{
char **temp;
char **tempNew;
char lineInfo[200]
temp = new char*[5];
tempNew = new char*[5];
for (int i=0; i<5; i++)
{
temp[i] = new char[200];
is.getline(lineInfo, sizeof(lineInfo));
int length = strlen(lineInfo);
for (int z=0; z < length; z++)
{
if(lineInfo[z] == '= ' ){ //HOW DO I CHECK IF THERE IS NOTHING AFTER THE LAST CHAR
lineInfo [length - (z+1)] = lineInfo [length];
cout << lineInfo << endl;
strncpy(temp[i], lineInfo, sizeof(lineInfo));
}
else{
tempNew[i] = new char[200];
strncpy(tempNew[i], lineInfo, sizeof(lineInfo));
}
}
}
如果您需要查找“:”
#include <cstring>
只是auto occurance = strstr(string, substring);
文档在这里 。
如果事件不是ptr的空值,则从get行开始查看事件是否在行的末尾。 如果不是,那么您的价值就是一切:
使用std::string
容易std::string
。
// Read high score
int high_score;
my_text_file.ignore(10000, ':');
cin >> high_score;
// Read player name
std::string player_name;
my_text_file.ignore(10000, ':');
std::getline(my_text_file, player_name);
// Remove spaces at beginning of string
std::string::size_type end_position;
end_position = player_name.find_first_not_of(" \t");
if (end_position != std::string::npos)
{
player_name.erase(0, end_position - 1);
}
// Read kills
unsigned int number_of_kills = 0;
my_text_file.ignore(':');
cin >> number_of_kills;
// Read "Map" line
my_text_file.ignore(10000, '\n');
std::string map_line_text;
std::getline(my_text_file, map_line_text);
// Read "Text" line
std::string text_line;
std::getline(my_text_file, text_line);
如果您坚持使用C样式的字符串( char
数组),则必须使用更复杂,更不安全的功能。 查找以下功能:
fscanf, strchr, strcpy, sscanf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.