Reg*_*gEx 3 c++ linux windows string size
我偶然发现了string :: substr的奇怪行为.通常我在Eclipse + MinGW 上的Windows 7上编码,但是当我在笔记本电脑上工作时,在Linux中使用Eclipse (Ubuntu 12.04),我发现结果有所不同.
我正在使用填充了文本行的vector <string>.其中一个步骤是从行中删除最后一个字符.
在win7 Eclipse中我做了:
for( int i = 0; i < (int)vectorOfLines.size(); i++ )
{
vectorOfTrimmedLines.push_back( ((string)vectorOfLines.at(i)).substr(0, ((string)vectorOfLines.at(i)).size()-1) );
}
Run Code Online (Sandbox Code Playgroud)
它的工作方式与预期相同(从每行中删除最后一个字符)
但在Linux中,这段代码不会修剪.相反,我需要像这样做:
// -2 instead -1 character
vectorOfTrimmedLines.push_back( ((string)vectorOfLines.at(i)).substr(0, ((string)vectorOfLines.at(i)).size()-2) );
Run Code Online (Sandbox Code Playgroud)
或使用其他方法:
vectorOfTrimmedLines.push_back( ((string)vectorOfLines.at(i)).replace( (((string)vectorOfLines.at(i)).size()-2),1,"",0 ));
Run Code Online (Sandbox Code Playgroud)
当然Linux方法在Windows上工作错误(修剪2个最后一个字符,或者在最后一个字符之前替换一个字符).
问题似乎是myString.size()返回Windows中的字符数,但在Linux中它返回的字符数为+ 1.可能是Linux上的新行字符?
作为C++和编程通用的新手,我想知道为什么会这样,以及如何做到平台无关.
我想知道的另一件事是:哪种方法更好(更快)substr或替换?
编辑:用于填充字符串的方法我写的这个函数:
vector< string > ReadFile( string pathToFile )
{
// opening file
ifstream myFile;
myFile.open( pathToFile.c_str() );
// vector of strings that is returned by this function, contains file line by line
vector< string > vectorOfLines;
// check if the file is open and then read file line by line to string element of vector
if( myFile.is_open() )
{
string line; // this will contain the data read from current the file
while( getline( myFile, line ) ) // until last line in file
{
vectorOfLines.push_back( line ); // add current line to new string element in vector
}
myFile.close(); // close the file
}
// if file does not exist
else
{
cerr << "Unable to open file." << endl; // if the file is not open output
//throw;
}
return vectorOfLines; // return vector of lines from file
}
Run Code Online (Sandbox Code Playgroud)
不同操作系统上的文本文件不相同.Windows使用双字节代码标记行的结尾:0x0D,0x0A.Linux使用一个字节0x0A.getline(以及大多数其他输入函数)知道为其编译的OS的约定; 当它读取操作系统用来表示一行结束的字符时,它会用'\n'替换字符.因此,如果您在Windows下编写文本文件,则行以0x0D,0x0A结尾; 如果您在Linux下读取该文本文件,getline看到0x0D并将其视为普通字符,则它会看到0x0A,并将其视为该行的结尾.
因此,当您将文本文件从一个系统移动到另一个系统时,必须将文本文件转换为本机表示.ftp知道怎么做.如果您在虚拟框中运行,则必须在切换系统时手动执行转换.tr从Unix命令行可以很简单.
| 归档时间: |
|
| 查看次数: |
2337 次 |
| 最近记录: |