C++ 摆脱空字符串行

C++ getting rid of empty string rows

您好,这段代码在 5 分钟前就可以正常工作,完全符合我的需要。

数据为:

Set Field [G],Sheet Resistivity (Gavg) [ohm/sqr]
0.0000E+0,
0.0000E+0,7.270620E+2
1.0000E-2,
1.0000E-2,7.271280E+2
-1.0000E-2,
-1.0000E-2,
-1.0000E-2,7.271290E+2

我的代码是:

#include <iostream>
#include <fstream>

using namespace std;

int main(){

  ifstream ip("/Users/10Exahertz/Documents/Hall Data/Test/data.txt");

  if(!ip.is_open()) std::cout << "ERROR: File Open" << '\n';

  string x;
  string y;

  while(getline(ip,x,',')){
    getline(ip,y,'\n');

   if(y!="")
    std::cout <<x<<","<< y << '\n';

  }
  ip.close();
}

就像我 5 分钟前说的那样有效,它摆脱了带有空 y 字符串的行,一切都很好。但后来我回到原始数据文件,它在那里不起作用。我很困惑,所以我将原始数据放入 data.txt,现在那个数据也不起作用了。老实说,我很困惑,但是在那个 if 循环中最好的条件是什么才能让它起作用。

听起来你可能有一些空白在偷偷摸摸。我会使用从 this answer 到 trim 的解决方案 y 字符串中的空白只是为了确定:

#include <iostream>
#include <algorithm> 
#include <cctype>
#include <locale>
#include <fstream>

using namespace std;

// trim from start (in place)
static inline void ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
        return !std::isspace(ch);
    }));
}

int main() {
    [...]
    while(getline(ip,x,',')){
        getline(ip,y,'\n');
        ltrim(y);

        if(y!="")
            std::cout <<x<<","<< y << '\n';
    }
}